3Sum Closest——LeetCode

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

题意就是给定一个数组,一个target,在数组中寻找一个三元组之和最接近target的值,这个题是之前3Sum的变形,不同的是这个题没有重复元素,而且设定解唯一。

我的思路是:跟之前的3sum一样,保留左右各一个pointer,遍历的时候,有left和right两个游标,left就从i+1开始,right就从数组最右length-1开始,如果i、left、right三个元素加起来等target,那么就可以加入结果的List中了,如果sum-target>0,那么说明sum比较大,right应该向左移动,反之left向右移动。

Talk is cheap>>

   public int threeSumClosest(int[] num, int target) {
        if (num == null || num.length < 3) {
            return 0;
        }
        int min = Integer.MAX_VALUE;
        int res=0;
        Arrays.sort(num);
        for (int i = 0; i < num.length - 2; i++) {
            int left = i + 1;
            int right = num.length - 1;
            while (left < right) {
                int sum = num[i] + num[left] + num[right];
//                System.out.printf(i+" "+sum);
                if (sum == target) {
                    return target;
                }
                if (min>=abs(sum-target)){
                    min = abs(sum-target);
                    res=sum;
                }
                if (sum-target>0){
                    right--;
                }else {
                    left++;
                }
            }
        }
        return res;
    }
    public int abs(int a){
        return Math.abs(a);
    }
原文地址:https://www.cnblogs.com/aboutblank/p/4382498.html