美文网首页
16. 3Sum Closest

16. 3Sum Closest

作者: 窝火西决 | 来源:发表于2019-06-10 16:22 被阅读0次

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

题目

找和最接近target的三个数,返回他们的和

思路

和15号问题差不多,把判断条件改一下即可

代码

public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len =nums.length;
        int res=Integer.MAX_VALUE;//存最后的和
        int minv=Integer.MAX_VALUE;//存最小的差
        for (int i = 0; i < nums.length; i++) {
            if (i>0&&nums[i]==nums[i-1]) {
                continue;
            }
            int begin = i+1;
            int end=len-1;
            while (begin<end) {
                int sum=nums[i]+nums[begin]+nums[end];
                int minus=sum-target;
                if (minus==0) {
                    return sum;
                }else if (minus>0) {
                    if (minus<minv) {
                        minv=minus;
                        res=sum;
                    }
                    end--;
                }else {
                    if (-minus<minv) {
                        minv=-minus;
                        res=sum;
                    }
                    begin++;
                }
            }
        }
        return res;
    }

相关文章

  • LeetCode #16 2018-07-28

    16. 3Sum Closest Given an array nums of n integers and an...

  • Day3

    16. 3Sum Closest Given an array S of n integers, find thr...

  • LeetCode 16. 3Sum Closest

    16. 3Sum Closest Given an array S of n integers, find thr...

  • 16. 3Sum Closest

    题目: Given an array S of n integers, find three integers i...

  • 16. 3Sum Closest

    题目: 给定一个nums由n个整数和一个整数组成的数组target,找出三个整数nums,使总和最接近target...

  • 16. 3Sum Closest

    Given an array nums of n integers and an integer target, ...

  • 16. 3Sum Closest

    Description Given an array S of n integers, find three in...

  • 16. 3Sum Closest

    Given an array nums of n integers and an integer target, ...

  • 16. 3Sum Closest

    Description Given an array S of n integers, find three in...

  • 16. 3Sum Closest

    先排序,然后左右夹逼,每次当sum-target < diff 用diff记录下最小距离

网友评论

      本文标题:16. 3Sum Closest

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