leetcode 167 Two Sum II - Input array is sorted
z

167. 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. 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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


第一想到的方法是之前two sum 1中的方法,使用一个hashmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] result = new int[2];
for(int i=0;i<numbers.length;i++){
if(m.containsKey(target-numbers[i])){
result[0] = m.get(target-numbers[i])+1;
result[1] = i+1;
}
else{
m.put(numbers[i], i);
}
}
return result;
}
}

但是这里考虑到输入已经排序,而且一定存在一个解,那么可以直接比较:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int[] twoSum(int[] numbers, int target) {
int lo = 0;
int hi = numbers.length - 1;
int[] result = new int[2];
while (lo < hi){
if (numbers[lo] + numbers[hi] == target){
result[0] = lo+1;
result[1] = hi+1;
break;
}
else if(numbers[lo] + numbers[hi] < target){
lo++;
}
else{
hi--;
}
}
return result;
}
}