16. 3Sum Closest

作者: d1497e8e780a | 来源:发表于2019-02-21 19:19 被阅读9次

Swift

52ms

class Solution {
    func threeSumClosest(_ nums: [Int], _ target: Int) -> Int {
        let copyNums = nums.sorted{$0 < $1}
        if copyNums.count < 3 {
            return 0
        }
        var res = 0; var dist = Int32.max
        
        for i in 0..<copyNums.count - 2 {
            if (i > 0 &&  copyNums[i] == copyNums[i - 1] ) {
                continue
            }
            var j = i + 1
            var k = nums.count - 1
            var sum = 0
            while  j < k {
                sum = copyNums[i] + copyNums[j] + copyNums[k]
                if sum == target {
                    return sum
                }
                if (abs(sum - target) < dist) {
                    dist = Int32(abs(sum - target))
                    res = sum
                }
                if sum < target {
                    j += 1
                } else {
                    k -= 1
                }
            }
        }
        return  res
    }
}

C++

12ms

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
       if (nums.size() < 3) return 0;
    sort(nums.begin(), nums.end());
    int closet = nums[0] + nums[1] + nums[2];
    for(int first = 0; first < nums.size() -2; first++)
    {

       if(first > 0 && nums[first] == nums[first -1]) continue;
       int second = first + 1;
       int third = nums.size() -1;
       while (second < third) {
           int curSum = nums[first] +nums[second] + nums[third];
           if (curSum == target) return curSum;
           if (abs(target - curSum) < abs(target - closet)) {
               closet = curSum;
           }
           if (curSum < target) {
                ++second;
           } else {
                --third;
           }
       }
    }
    return closet; 
    }
};

相关文章

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