3Sum Closest

来源:互联网 发布:欧洲文明史 知乎 编辑:程序博客网 时间:2024/06/03 19:34

有了3Sum的基础,这个本来应该很好解决,

但是自己却提交了5次。。。。咋搞的,到底要比较的是啥,下面咋那么多次错误

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

        // write your code here
        if (numbers == null || numbers.length < 3) {
            return -1;
        }
        Arrays.sort(numbers);
        //1 int closest = Ingeter.MAX_VALUE;
        int closest = Integer.MAX_VALUE;
        for (int i = 0; i < numbers.length - 2; i++) {
            int left = i + 1;
            int right = numbers.length - 1;
            while (left < right) {
                int sum = numbers[i] + numbers[left] + numbers[right];
                //2 if (Math.abs(target, sum) <= closest) {
                int sub = Math.abs(target - sum);
                //if (sub < closest) {
                if (sub < Math.abs(target - closest)) {
                    //3 closest = Math.abs(target - sum);
                    closest = sum;
                    //4 left++;
                //4 } else {
                    //4 right--;
                }
                //right--;
                if (sum > target) {
                    right--;
                } else {
                    left++;
                }
            }
        }
        return closest;
    }
0 0