作为leetcod开篇第一题,一定被大家熟知,解法也有多种:1,夹逼法,复杂度:NlogN+N;2,HashMap法,N,因为用空间换时间;(其实是N平方,但是利用了HashMap中查询操作复杂度为1,把N变为了1,所有就有 N*N -> N*1)
写在这里,是因为和上一道first bad version 解法类似,归类在一起,下面是夹逼法解题,时间复杂度是NlogN,空间复杂度为1,代码如下:
结果发现是错的!!!因为题目要求返回的是index,一排序就失去原有index了,汗!!!所以这个夹逼法只能在返回两个数的时候才能用,返回index就不能排序!!!
注意!以下代码不能用于返回index的解题要求,其实我之前也总结过:1st round, 1 2Sum
public class Solution {
public int[] twoSum(int[] nums, int target) {
Arrays.sort(nums); // NOT Array.sort(), always have s in the end
int left=0;
int right=nums.length-1;
while(left<right){
int sum=nums[left]+nums[right];
if(sum==target) break;
else if(sum<target) left++;
else right--;
}
return new int[]{left, right};
}
}
下面是利用HashMap的代码,时间复杂度低,仅为N,空间复杂度为N,因为用空间换时间:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result= new int[2];
Map<Integer, Integer> map = new HashMap<>(); // <elem, index>
for(int i=0; i<nums.length; i++){
if(map.containsKey(target-nums[i])){ // containsKey, not contains
result[0]=map.get(target-nums[i]);
result[1]=i;
break;
}
else map.put(nums[i], i); // put(), not add()
}
return result;
}
}