LeetCode 16. 3Sum Closest

来源:互联网 发布:1050ti 知乎 编辑:程序博客网 时间:2024/05/16 01:22

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

    For example, given array S = {-1 2 1 -4}, and target = 1.    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).


same idea as Three Sum question: three pointers.

If use HashMap, it can be changed into Two Sum question.

#include <vector>#include <algorithm>#include <iostream>#include <climits>using namespace std;// Suppose such a triplet must exist.// inputs may contain duplicates.int threeSumCloset(vector<int>& nums, int target) {    sort(nums.begin(), nums.end()); // nlgn time complexity.    int i = 0;    int closetSum;    int minDiff = INT_MAX;    while(i < nums.size()) {    // o(n2) time complexity        if(i > 0 && nums[i] == nums[i-1]) {            i++;            continue;        }        int start = i + 1;        int end = nums.size() - 1;        while(start < end) {            if(start - 1 > i && nums[start] == nums[start - 1]) {                start++;                continue;            }            if(end + 1 < nums.size() && nums[end] == nums[end + 1]) {                end--;                continue;            }            int sum = nums[i] + nums[start] + nums[end];            if(abs(sum - target) < minDiff) {  // actually once we found a 0, we can just stop and return.                minDiff = abs(sum - target);                closetSum = sum;            }            if(sum >= target) end--;            else start++;        }        i++;    }    return closetSum;}int main(void) {    vector<int> nums{-1, 2, 1, 4};    int res = threeSumCloset(nums, 1);    cout << res << endl;}

0 0
原创粉丝点击