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

超时的代码:

public class Sum22 {
    public int[] twoSum(int[] numbers, int target) {
        int result[] = new int[2];
        if(numbers[0]>target){
            return result;
        }
        
        
        for (int i = 0; i < numbers.length; i++) {
            for (int j = i+1; j < numbers.length; j++) {
                if(numbers[i]+numbers[j]==target){
                    result[0]=i+1;
                    result[1]=j+1;
                    return result;
                }
            }
        }
        return result;
    }
}

Accept代码:如果数组已经排好序了,就尽可能的使用while(),左右遍历

public class Sum22 {
    public int[] twoSum(int[] numbers, int target) {
        int result[] = new int[2];
        if(numbers[0]>target){
            return result;
        }
        int left = 0;
        int right = numbers.length-1;
        while(left<right){
            if(numbers[left]+numbers[right]==target){
                result[0]=left+1;
                result[1]=right+1;
                break;
            }else if(numbers[left]+numbers[right]<target){
                left++;
            }else {
                right--;
            }
        }
        return result;
    }
}

 

posted on 2017-12-11 09:14  Michael2397  阅读(98)  评论(0编辑  收藏  举报

导航