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.less

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.spa

You may assume that each input would have exactly one solution.指針

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

就是一個雙指針夾比的題目。blog

 1 public class Solution {
 2     public int[] twoSum(int[] numbers, int target) {
 3         int[] result = new int[2];
 4         if(numbers == null && numbers.length < 2) return result;
 5         int i = 0, j = numbers.length - 1;
 6         while(i < j){
 7             int sum = numbers[i] + numbers[j];
 8             if(sum > target) j --;
 9             else if(sum < target) i ++;
10             else{
11                 result[0] = i + 1;
12                 result[1] = j + 1;
13                 break;
14             }
15         }
16         return result;
17     }
18 }
相關文章
相關標籤/搜索