最接近的三数之和 (3Sum Closest)

 

思路:

// @Title: 最接近的三数之和 (3Sum Closest)
// @Author: qisiii
// @Date: 2024-04-12 22:41:53
// @Runtime: 13 ms
// @Memory: 42.1 MB
// @comment: 
// @flag: 
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int value = nums[i] + nums[left] + nums[right];
                //在坐标轴上可以明显察觉出用V和T作差的绝对值更能表明距离
                if ( Math.abs(value-target )<Math.abs( ans-target)) {
                    ans = value;
                }
                if (value > target) {
                    right--;
                } else if (value < target) {
                    left++;
                } else {
                    return target;
                }
            }

        }
        return ans;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18