LeetCode | Two Sum

题目

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

分析

最原始的做法就是,先给数组排序,然后首尾指针(数组索引)向中间移动即可。这样的时间复杂度是O(nlgn) + O(n) = O(nlgn)。由于需要返回索引,排序时还要记录索引号,空间复杂度也是O(n)。

另一种做法就是,遍历两边数组,第一遍把每个元素以元素值为键,以索引为值存入哈希表中;第二遍遍历时,查询哈希表中是否有相加为target的键值。这种方法时间复杂度O(n),空间复杂度O(n)。

但是从LeetCode上测试的时间结果上来看,两种方法在大数据上用时差不多。

解法1

import java.util.Arrays;

public class TwoSum {
	// the element of index array
	class E implements Comparable<E> {
		int index;
		int number;

		public E(int index, int number) {
			this.index = index;
			this.number = number;
		}

		@Override
		public int compareTo(E that) {
			if (this.number > that.number) {
				return 1;
			} else if (this.number < that.number) {
				return -1;
			}
			return 0;
		}
	}

	public int[] twoSum(int[] numbers, int target) {
		assert numbers != null && numbers.length > 1;
		
		int[] ret = new int[2];

		// init index array
		int N = numbers.length;
		E[] elements = new E[N];
		for (int i = 0; i < N; ++i) {
			elements[i] = new E(i + 1, numbers[i]);
		}

		// sort
		Arrays.sort(elements);
		
		// tranverse from both side
		int i = 0;
		int j = N - 1;
		while (j > i) {
			if (elements[i].number + elements[j].number == target) {
				int index1 = elements[i].index;
				int index2 = elements[j].index;
				
				// adjust the output
				if (index1 > index2) {
					ret[0] = index2;
					ret[1] = index1;
				} else {
					ret[0] = index1;
					ret[1] = index2;
				}
				break;
			} else if (elements[i].number + elements[j].number > target) {
				--j;
			} else {
				++i;
			}
		}
		return ret;
	}
}
解法2
import java.util.HashMap;

public class TwoSum {
	private HashMap<Integer, Integer> records = new HashMap<Integer, Integer>();

	public int[] twoSum(int[] numbers, int target) {
		int[] ret = new int[2];
		records.clear();

		// generate the hashmap
		for (int i = 0; i < numbers.length; ++i) {
			records.put(numbers[i], i + 1);
		}

		// tranverse
		for (int i = 0; i < numbers.length; ++i) {
			int other = target - numbers[i];
			if (records.containsKey(other)) {
				int j = records.get(target - numbers[i]);
				if (i + 1 > j) {
					ret[0] = j;
					ret[1] = i + 1;
				} else {
					ret[0] = i + 1;
					ret[1] = j;
				}
				break;
			}
		}
		return ret;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值