1. 程式人生 > >【leetcode】16 3Sum Closest

【leetcode】16 3Sum Closest

描述

給定一個數字集合 S 以及一個數字 target,需要從集合中找出3個數字的和與這個 target的值最接近(絕對值最小)

樣例

 Input: S = [-1, 2, 1, -4], target = 1
 Output: 2

思路

首先排序,之後確定一個數字的前提下,再利用雙指標從兩端向中間掃描,求
min | a+b+c - target| ,其中 a,b ,c 是 集合中數字。

程式碼

#include<iostream>
#include<string>
#include<vector>
#include <set>
#include <algorithm>
#include <cmath>
#include <climits>

using namespace std;

class Solution {
public:
     int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int maxdiff = INT_MAX;
        int res = 0;
        int len = nums.size();

        for(int i=0;i<len-2;i++){
            int start = i+1;
            int end = len-1;
         
            while(start<end){
                 int threeSum = nums[i] + nums[start] + nums[end];
                 int tempdiff = threeSum - target; 
                if(tempdiff == 0){
                    return threeSum;
                }
                else if(abs(tempdiff) < maxdiff){
                    maxdiff = abs(tempdiff);
                    res = threeSum;               
                }
                if(threeSum > target){
                    end--;
                }
                else if(threeSum < target){
                    start++;
                }
            }
        }
        return res;
    }
};

int main(){
   // vector<int> nums{0,2,1,-3};
    vector<int> nums{-1, 2, 1, -4};
    int target = 1;
    Solution ss;
    cout<<ss.threeSumClosest(nums,target)<<endl;

}

參考連結

原題連結
3sum維基百科