美文网首页
16. 3Sum Closest

16. 3Sum Closest

作者: wtmxx | 来源:发表于2018-02-07 22:08 被阅读0次

3Sum思路相同

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int mindis = Integer.MAX_VALUE;
        Arrays.sort(nums);
        int sum = 0;
        int len = nums.length;
        
        for(int i=0;i<len-2;i++){
            while(i>0&&i<len-2&&nums[i]==nums[i-1])i++;
            int p = i+1,q = len-1;
            while(p<q){
                int tmp = nums[i]+nums[p]+nums[q]-target;
                if(Math.abs(tmp)<mindis){
                    mindis = Math.abs(tmp);
                    sum = tmp+target;
                }
                if(tmp<0){
                    p++;
                }else if(tmp>0){
                    q--;
                }else{
                    return target;
                }
            }
        }
        return sum;
    }
}

相关文章

  • 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/dffzzxtx.html