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

16. 最接近的三数之和

作者: 码蹄疾 | 来源:发表于2018-07-01 22:20 被阅读239次

知乎ID: 码蹄疾
码蹄疾,毕业于哈尔滨工业大学。
小米广告第三代广告引擎的设计者、开发者;
负责小米应用商店、日历、开屏广告业务线研发;
主导小米广告引擎多个模块重构;
关注推荐、搜索、广告领域相关知识;

题目

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

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

分析

排序,和上一道题类似然后把三个数求和的解就转化为两个数相加等于某个数。
求解两个数相加等于某个数,用双指针法即可。不需要处理重复问题,还降低了难度。

Code

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int res = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length; i++) {
            int l = i + 1;
            int r = nums.length - 1;
            while (l < r) {
                int current = nums[i] + nums[l] + nums[r];
                if (Math.abs(res - target) > Math.abs(target - current)) {
                    res = current;
                }
                if (current < target) {
                    l++;
                } else {
                    r--;
                }
            }
        }
        return res;
    }
}
扫码关注

相关文章

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

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

  • 力扣每日一题:16.最接近的三数之和 双指针解法

    16.最接近的三数之和 https://leetcode-cn.com/problems/3sum-closest...

  • 16.最接近的三数之和

    16.最接近的三数之和 题目链接:https://leetcode-cn.com/problems/3sum-cl...

  • 16. 三数之和最接近

    题目 给定一个整数数组 nums 和一个目标数 target,在 nums 中找出三个数,要求其和与 targe...

  • algrithrom

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

  • 16. 最接近的三数之和

    一、题目原型: 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整...

  • 16.最接近的三数之和

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

  • 16. 最接近的三数之和

    知乎ID: 码蹄疾码蹄疾,毕业于哈尔滨工业大学。小米广告第三代广告引擎的设计者、开发者;负责小米应用商店、日历、开...

  • 16. 最接近的三数之和

    16.最接近的三数之和 给定一个包括n个整数的数组nums和 一个目标值target。找出nums中的三个整数,使...

  • 16.最接近的三数之和

    给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和...

网友评论

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

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