首页 > 代码库 > 167. Two Sum II - Input array is sorted

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.

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

链接: http://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

2/19/2017, Java

没有想到用binary search的方法,就是两个指针每次走1步的算法。

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

 

167. Two Sum II - Input array is sorted