标签:
Q: 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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
public class Solution2{
// O(n) runtime, O(n) space;
// We have two pointers, start and end,
// firstly, we add start and end, because the array is sorted in ascending order,
//if the sum is smaller than our target, we just increase the start point;
// if the sum is greater than our target, we just decrease the end point,
//keep doing this, until the sum is equal to our target.
public int[] twoSum(int[] numbers, int target) {
int i = 0, j = numbers.length - 1;
while(i < j){
if(numbers[i] + numbers[j] < target){
i++;
} else if(numbers[i] + numbers[j] > target){
j--;
} else {
return new int[] {i+1, j+1};
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
Two Sum II - Input array is sorted(leetcode167) - Solution2
标签:
原文地址:http://www.cnblogs.com/caomeibaobaoguai/p/4873386.html