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

最接近的三数之和

作者: 二进制的二哈 | 来源:发表于2019-11-29 17:45 被阅读0次

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

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

例如:

给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

这道题跟“三数之和”那道题思路差不多,依旧是排序+双指针的思路,只需要做稍微的改动即可。
Java代码:

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int ans = target;
        Integer min = null;//最小差值(取绝对值)
        if(nums != null && nums.length > 2){
            //对数组排序
            Arrays.sort(nums);//-4,-1,1,2
            for(int i = 0;i<nums.length;i++){
                //避免重复计算
                if(i > 0 && nums[i] == nums[i-1])
                    continue;
                int left = i + 1;
                int right = nums.length - 1;
                while(left < right){
                    int sum = nums[i] + nums[left] + nums[right];
                    if(sum == target)
                        return target;
                    int tmp = sum - target;//差值
                    if(tmp > 0){
                        //说明现在的总和比target大,right就要往左移动
                        right--;
                    }else{
                        //说明现在的总和比target小,left就要往右移动
                        left++;
                    }
                    if(min == null || Math.abs(tmp) < min){
                        ans = sum;
                        min = Math.abs(tmp);
                    }
                }
            }
        }
        return ans;
    }
}

相关文章

  • 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...

  • 双指针法(算法)

    案例: 盛最多水的容器、三数之和、最接近的三数之和 双指针法一般对应于有序数组的情况,通过调节指针(左右移动),...

网友评论

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

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