leetcode 167

两数之和 II - 输入有序数组

Posted by Static on July 20, 2020

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

题目描述


分析

1. 遍历

2. 双指针


代码实现

public enum Q167 {
    instance;

    public int[] twoSum(int[] numbers, int target) {

        int l=numbers.length;
        int result[]=new int[2];
        for(int i=0;i<l;i++){
            for(int j=i-1;j>=0;j--){
                if(numbers[j]+numbers[i]==target){
                    result[0]=j+1;
                    result[1]=i+1;
                }else if(numbers[j]+numbers[i]<target){
                    break;
                }
            }
        }
        return result;
    }

    public int[] twoSum1(int[] numbers, int target) {
        int size=numbers.length;
        int result[]=new int[2];

        int l=0,r=size-1;
        while (l<r){
            if(numbers[l]+numbers[r]==target){
                result[0]=l+1;
                result[1]=r+1;
                break;
            }else if(numbers[l]+numbers[r]>target){
                r--;
            }else {
                l++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        // assert [1,2]
        SystemUtil.print(Q167.instance.twoSum(new int[]{2, 7, 11, 15},9));
        SystemUtil.print(Q167.instance.twoSum1(new int[]{2, 7, 11, 15},9));

        // assert [1,2]
        SystemUtil.print(Q167.instance.twoSum(new int[]{-1,0},-1));
        SystemUtil.print(Q167.instance.twoSum1(new int[]{-1,0},-1));
    }
}

Never be afraid to reach for the stars, because even if you fall, you’ll always be wearing a parent-chute.

永远不要害怕去摘星星,因为就算你跌下来,你永远有“父母牌”降落伞防身。