LeetCode OJ算法题(一):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(n^2)的复杂度是不足以拿到offer的,于是这种方法华丽丽的TLE了,那么有什么方法能够降低时间复杂度呢?很容易想到HashMap,有数组元素作为Key,数组下标(从1开始)作为Value,判断target-key的元素在不在HashMap中即可(注意Input可能为0,也可能为负值,提交的时候几次都忘记了这点- -!),那么可以开始用迭代器进行遍历了。

但是,到这里并没有做完,仍有bug,因为对于有相同元素的输入,加入HashMap后下标会被覆盖掉,例如{2,2,5,7},4的测试样例,返回值会是{2,2}而不是期望的{1,2}。改进方法可以投一下机,题目告诉我们每个输入只有一个解,那么如果有相同元素出现,且会影响我们结果的情况,一定是这个被重复的元素就是问题的解,即为target/2!!!

很好,加入判断后漂亮的AC了~

public class No1_TwoSum {
	public static void main(String[] args){
		int[] r = twoSum(new int[]{0,4,3,0}, 0);
		System.out.println(""+r[0]+" "+r[1]);
	}
	public static int[] twoSum(int[] numbers, int target){
//		for(int i=0;i<numbers.length-1;i++){
//			for(int j=i+1;j<numbers.length;j++){
//				if(numbers[i]+numbers[j] == target){
//					return new int[]{i+1,j+1};
//				}
//			}
//		}
		HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
		for(int i=0;i<numbers.length;i++){
			if(map.get(numbers[i]) == null){
				map.put(numbers[i], i+1);
			}
			else if(numbers[i] == target/2)
				return new int[]{map.get(numbers[i]),i+1};
		}
		Iterator<Entry<Integer, Integer>> it = map.entrySet().iterator();
		while(it.hasNext()){
			int n = it.next().getKey();
			if(map.get(target - n) != null)
				return map.get(n)<map.get(target-n)?new int[]{map.get(n),map.get(target-n)}:new int[]{map.get(target-n),map.get(n)};
		}
		return null;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值