Sword Finger Offer Interview Question 57: The sum is the number of s

For this question, my idea is to set two array index pointers index_p and index_l, one to the head and one to the end, because the given arrays are all positive numbers, and they are sorted from small to large. This means that if you first calculate the sum of the corresponding two numbers, if it is greater than the given value, you can move the tail pointer forward and continue the calculation until the state of the sum changes. If it is equal, output directly; if it is less than, then The head pointer moves forward.

My code, 5mins direct seconds, is still the same as the answer, which is really cool.

    public int[] twoSum(int[] nums, int target) {
        int index_p = 0;
        int index_l = nums.length - 1;
        while(index_p<index_l){
            if(nums[index_p] + nums[index_l] == target){
                return new int[]{nums[index_l],nums[index_p]};
            }else if(nums[index_p] + nums[index_l] > target){
                index_l--;
            }else if(nums[index_p] + nums[index_l] < target){
                index_p++;
            }
        }
        return null;
    }

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/115027731