[LeetCode] #16 最接近的三数之和

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

[LeetCode] #15 三数之和思路一样

排序、双指针

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        int res = nums[0] + nums[1] + nums[n-1];
        Arrays.sort(nums);
        for(int i = 0; i < n; i++){
            int left = i + 1, right = n - 1;
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            while(left < right){
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == target) return target;
                if (Math.abs(sum - target) < Math.abs(res - target)) res = sum;
                if (sum > target) {
                    while (left < right && nums[right - 1] == nums[right]) right--;
                    right--;
                } else {
                    while (left < right && nums[left + 1] == nums[left]) left++;
                    left++;
                }

            }
        }
        return res;
    }
}

知识点:

总结:

 

posted @ 2021-09-29 22:33  1243741754  阅读(16)  评论(0编辑  收藏  举报