美文网首页
LeetCode-16. 最接近的三数之和

LeetCode-16. 最接近的三数之和

作者: 悠扬前奏 | 来源:发表于2020-06-21 00:28 被阅读0次

题目

描述

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

示例

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

提示

3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解答

思路

应该和三数和为0的思路一致:

  1. 排序后双指针移动查找符合条件的第三个指针。
  2. 原始数组中数字可能重复,需要跳过

代码

    public int threeSumClosest(int[] nums, int target) {
        if (nums.length == 3) {
            return nums[0] + nums[1] + nums[2];
        }
        int n = nums.length;
        Arrays.sort(nums);
        int res = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < n - 2; i++) {
            // 需要和前一个数不同
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < n - 1; j++) {
                // 需要和前一个数不同
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                for (int k = j + 1; k < n; k++) {
                    if (Math.abs(nums[i] + nums[j] + nums[k] - target)
                            < Math.abs(res - target)) {
                        res = nums[i] + nums[j] + nums[k];
                        if (res == target) {
                            return res;
                        }
                    }
                }
            }
        }
        return res;
    }
}

相关文章

  • LeetCode-16. 最接近的三数之和

    题目 描述 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • LeetCode-16 最接近的三数之和

    题目:16. 最接近的三数之和 难度:中等 分类:数组 解决方案:双指针 今天我们学习第16题最接近的三数之和,这...

  • 双指针总结

    左右指针 主要解决数组中的问题:如二分查找 盛最多水的容器 三数之和 四数之和 最接近三数之和 快慢指针 主要解决...

  • LeetCode练习day1-数组相关

    LeetCode16 最接近的三数之和 相似题目:LeetCode15 三数之和 题目详情 给你一个长度为 n 的...

  • 最接近的三数之和

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/3sum...

  • 最接近的三数之和

    题目 思路 题解

  • 最接近的三数之和

    题目地址 1.思路 第一步很容易想到的就是降维处理,三个数相当于三维,那么我确定一个数的时候只剩下2维,这样就把问...

  • 最接近的三数之和

    leetcode 16 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中...

  • 最接近的三数之和

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/3sum-c...

网友评论

      本文标题:LeetCode-16. 最接近的三数之和

      本文链接:https://www.haomeiwen.com/subject/uwrqtktx.html