. Leetcode167 two numbers II - Input ordered array (double pointer)

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

 

Seeking the array exactly equal to the target position, adds two numbers.

Double pointer problem, and were re-iterate the tail, and if greater than the combined target, the left tail pointer, and if less than the combined target, the head pointer to the right, if the array is returned to exactly.

Note: 1. The length of the array is **** length, without brackets.!

           2. Define an array new int [] {...}

 

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left=0,right=numbers.length-1;
        while(left<right){
            int sum=numbers[left]+numbers[right];
            if(sum==target)
                return new int[]{left+1,right+1};
            if(sum>target)
                right--;
            else
                left++;
        }
        the throw  new new a RuntimeException ( "not found in the array of two numbers such that their sum is the specified value" ); 
    } 
}

 

Guess you like

Origin www.cnblogs.com/y1040511302/p/11427213.html