Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, 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.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
这题相比开篇的Two Sum相比更为简单,因为这个是已经sorted过的array, 凡是这种sorted过的,我第一想法就是用binary search,或者根据数与数之间关系找到个shortcut。在这里因为是先做了two sum起,所以我一开始只是稍微改写了下之前的算法,利用倒着添加数来确保小的数在前面。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = nums.length-1; i >= 0; i--){ //区别点,倒着循环
int complete = target - nums[i];
if(complete>= 0 && map.containsKey(complete)){ //找的匹配数一定是非负,所以complete大于等于0,这样可以减少运行时间
return new int[]{i+1, map.get(complete)+1};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
但是这个runtime 是4ms, 在LeetCode上面只能beats 23.12%的Java submissions。我觉得是因为我没有好好利用sorted这个性质,所以先尝试用了个错误示范,用binary search(时间复杂度肯定变高O(nlogn))。
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length-1; i++){
int start = i;
int end = nums.length - 1;
int gap = target - nums[i];
while(start <= end){
int temp = start + (end - start)/2;
if(temp == i){ //避免用同一个数2次
temp = i+1;
}
if(nums[temp] == gap){
return new int[]{i+1, temp+1};
}
else{
if(nums[temp]>gap){
end = temp - 1;
}
else{
start = temp + 1;
}
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
在写二分法的时候发现各种问题,还是基础不够扎实。。。 然后很重要一点是需要加上一个条件判断是否temp == i, 来避免使用同一个数2次。
以上都不是优解,后面看到讨论区有人利用俩个pointer去限定区间最后找到解。这个是利用数组是sorted,解一定在某个子集里面存在,所以每次比较的时候其中一个pointer移动最后锁定最终解出来。
代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while(start < end){
int temp = nums[start] + nums[end];
if(temp == target){
return new int[]{start+1, end+1};
}
if(temp > target){
end--;
}
else{
start++;
}
}
throw new IllegalArgumentException("No two sum solution");
}
}