leetcode:TwoSum

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(n2),就想肯定会超时。然后,考虑到此题返回值为数组下标,就考虑到是否可以用map,之后再想求两个数的和,可以用map存储值和下标,然后查看是否包含target与当前值的差,这样就很好的解决了此类问题。

不过有两个地方需要注意,第一如果tagert恰好是当前值的两倍,这样可能会出现错误结果,认为当前值加两次就为target,

第二个跟第一个有关系,就是对于重复值的处理,需要考虑上述情况,这个时候当前值加两次的确为target,但是此种情况为正确的。

public int[] twoSum(int[] nums, int target) {
		 
		  Map<Integer,Integer> map=new HashMap<Integer,Integer>();
		  int[] res=new int[2];
		  if(nums.length<2) return res;
		  for(int i=0;i<nums.length;i++)
		  {
			  if(!map.containsKey(nums[i]))
			  {
				  map.put(nums[i], i+1);
				  //特殊处理target是当前值的两倍
				  if(map.containsKey(target-nums[i])&&target-nums[i]!=nums[i])
				  {
					  res[0]=map.get(target-nums[i]);
					  res[1]=map.get(nums[i]);
					  break;
				  }
				  
			  }
			  else
			  {
				//特殊处理target是当前值的两倍
				  if(target-nums[i]==nums[i])
				  {
					  res[0]=map.get(nums[i]);
					  res[1]=i+1;
					  break;
				  }
			  }
			  
		  }
		  return res;
	        
	    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值