题目
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.
我的思路
首先遍历,存入map,第二次遍历,判断target-current value 元素是否在map中,在,返回索引。
之前有two sum的题目,数组是无序的,我原来也是采用这个思路,但是可以优化,不需要遍历两次,一次就够,看下面的代码
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
这个思路肯定可行,但是无法利用有序这个特点,应该不是最优解法。
利用两个指针遍历,根据当前sum决定指针的移动情况,测试通过,但是只是超过了1%
的提交,时间复杂度太高。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
int p = 0;
int q = 1;
while (p < nums.length || q < nums.length) {
if (q > nums.length - 1) {
p++;
q = p + 1;
}
int sum = nums[p] + nums[q];
if (sum < target) {
q++;
}
if (sum == target) {
res[0] = p + 1;
res[1] = q + 1;
return res;
}
if (sum > target) {
p++;
q = p + 1;
}
}
return res;
}
}
优化解法
两个指针没有错,应该从两头开始。这样效率就会高很多,看了其他人的思路,修改一下:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
int p = 0;
int q = nums.length-1;
while (p < q) {
int sum = nums[p] + nums[q];
if (sum < target) {
p++;
}
if (sum == target) {
res[0] = p + 1;
res[1] = q + 1;
return res;
}
if (sum > target) {
q--;
}
}
return res;
}
}