Friday, April 14, 2017

[LintCode] 608 Two Sum - Input array is sorted 解题报告

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


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



Example
Given nums = [2, 7, 11, 15], target = 9
return [1, 2]



思路
既然已经排过序了,那么就从两边往当中走。
如果加起来大了,说明小的那个太小了,往右。
如果加起来小了,说明大的那个太大了,往左。



Code
public class Solution {
    /*
     * @param nums an array of Integer
     * @param target = nums[index1] + nums[index2]
     * @return [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum(int[] nums, int target) {
        // write your code here
        
        int[] res = new int[2];
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            if (nums[left] + nums[right] < target) {
                left++;
            }
            else if (nums[left] + nums[right] > target) {
                right--;
            }
            else {
                res[0] = left + 1;
                res[1] = right + 1;
                break;
            }
        }
        
        return res; 
    }
}