167.Two Sum II- Input array is sorted

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

1.Description(Medium)

Given an array of integers that is alreadysorted 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]

2.Code

跟经典的two sum P56 只有不用排序这一点不同。

注意在while里面return result;在最后return null;

如果直接在最后return result 会造成time limit exceed.

 public int[] twoSum(int[] nums, int target){
        if(nums==null || nums.length<2){
            return null;
        }
        int[] result=new int[2];
        int head=0;
        int tail=nums.length-1;
        while(head<tail){
            int sum=nums[head]+nums[tail];
            if(sum>target){
                tail--;
            }
            else if(sum<target){
                head++;
            }
            else{
                result[0]=head+1;
                result[1]=tail+1;
                return result;
            }
        }
        return null;
    }

Last updated