LeetCode -- sum of two numbers II - input ordered array

Given an ordered array in ascending order, find two numbers so that the sum of them is equal to the target number.

The function should return these two subscript values, index1 and index2, where index1 must be less than index2.

Explain:

The returned subscript values (index1 and index2) are not zero based.
You can assume that each input only corresponds to a unique answer, and you can't reuse the same element.
Example:

Enter: numbers = [2, 7, 11, 15], target = 9
Output: [1,2]
Explanation: the sum of 2 and 7 is equal to the target number 9. So index1 = 1, index2 = 2.

First of all, my code. Alas, my brain is stupid and my thinking is not good. I can only reluctantly optimize and double cycle through:

class Solution {
public int[] twoSum(int[] numbers, int target) {
    if(numbers==null||numbers.length==0)return null;
    int []res=new int[2];
        for(int index1=1;index1<numbers.length;index1++) {
            if((numbers[index1]+numbers[0])>target)continue;//For a small optimization, judge whether the sum of the current position and the minimum value is greater than the target, then reduce n-1 comparisons
            for(int index2=0;index2<index1;index2++) {
                if((numbers[index1]+numbers[index2])>target)break;//Continue to optimize. If it is greater than, do not compare later, and skip out of this layer
                if((numbers[index1]+numbers[index2])==target) {
                    res[0]=index2+1;
                    res[1]=index1+1;
                    return res;
                }
            }
        }
        return res;
    }
} 

Look at the solution of God, 66666, time 0ms, my 45ms ..

class Solution {
    //Because the array is ordered, then two pointers, one at the beginning and one at the end, and one layer of loop can ensure the result is correct
    public int[] twoSum(int[] numbers, int target) {
        int start=0;
        int end=numbers.length-1;
        int result[]=new int[2];
        while (start<end){
            int temp=numbers[start]+numbers[end];
            if(temp==target) {
                result[0]=start+1;
                result[1]=end+1;
                return result;
            }else if(temp<target){//If the sum is less than target, it means the start is too small! Because the end is already the largest
                int t=numbers[start];
                start++;
                while (numbers[start]==t){//Here, the optimization of Da Shen is to remove the value equal to start to compare (it feels like looking at the test case, and then corresponding to the optimization)
                    start++;
                }
            }else {
                int t=numbers[end];
                end--;
                while (numbers[end]==t){//The same token.
                    end--;
                }
            }
        }
        return result;
    }
}

Tags: less

Posted on Sat, 21 Mar 2020 11:48:46 -0400 by snteran