[leetcode] 16. 3Sum Closest

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int length = nums.length;
        int rr = Integer.MAX_VALUE;
        int result = 0;
        for (int i = 0; i < length; i++) {
            int x = nums[i];
            int target2 = target - x;
            int start = i + 1;
            int end = length - 1;
            while (start < end) {
                int sum = nums[start] + nums[end];
                int z = sum - target2;
                int d = Math.abs(z);
                if (sum < target2) {
                    start++;
                } else if (sum == target2) {
                    return target;
                } else {
                    end--;
                }
                if (rr > d) {
                    rr = d;
                    result = z;
                }
            }
        }
        return result + target;
    }
}
原文地址:https://www.cnblogs.com/Gryffin/p/6225112.html