TWO SUM ordered array of double-pointer ---

  Double pointer thought mainly used to traverse the array of pointers to two different elements, such cooperative task.

Two Sum ordered array of

Leetcode :167. Two Sum II - Input array is sorted (Easy)

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

Subject description:

  To find two numbers in an orderly array, and to make their target.

Analysis of ideas:

  Double pointer, a pointer to the smaller elements, pointing to a large element pointer smaller elements traversed from left to right, a pointer to the larger elements traversed from right to left.

  If the two elements and a pointer to the sum == target, then the required results obtained.

  If the sum> target, moving large elements of the sum becomes smaller;

  If the sum <target, moving large elements of the sum becomes larger;

Code:
public int[]twoSum(int []nums,int target){
    if(nums==null||nums.length<2)
        return null;
    int []res=new int [2];
    int small=0;
    int big=nums.length-1;
    while(small<big){
        if(nums[small]+nums[big]==target){
            res[0]=small+1;
            res[1]=big+1;
            return res;
        }else if(nums[small]+nums[big]<target){
            small++;
        }else{
            big--;
        }
    }
    return null
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11104369.html