16 3Sum Closest

类似的题目有
1 TwoSum
15 3Sum
18 4Sum

public static int threeSumClosest(int[] nums, int target) {

        Arrays.sort(nums);

        int minMinus = 10000;
        int result = 0;
        int sum = 0;

        for (int i = 0; i < nums.length; i++) {
            int j = i + 1;
            int k = nums.length - 1;
            while (j < k) {
                sum = nums[i] + nums[j] + nums[k];
                if (sum == target)
                    return 0;

                int minus = Math.abs(target - sum);

                if (minus < minMinus) {
                    minMinus = minus;
                    result = sum;
                }

                if (sum > target)
                    k--;
                else
                    j++;
            }
        }
        return result;
    }

你可能感兴趣的:(16 3Sum Closest)