[LeetCode] 3Sum Closest

来源:互联网 发布:手机淘宝查看卖家信誉 编辑:程序博客网 时间:2024/06/05 20:21

Sort the array, for each a, search the sum of b,c from two ends to the middle, while updating the minimum distance between the target.

Similar solution could apply to 3Sum and 4Sum problems.

class Solution {public:    int threeSumClosest(vector<int> &num, int target) {        int min_dist = INT_MAX;        int result;        sort(num.begin(),num.end());        for(int i=0;i<num.size();i++) {            int j=i+1,k=num.size()-1;            while(j<k) {                int tmp = num[i]+num[j]+num[k];                int dist = tmp>target?tmp-target:target-tmp;                if(dist<min_dist) {                    min_dist = dist;                    result = tmp;                }                if(tmp>target) k--;                else j++;            }        }        return result;    }};


0 0
原创粉丝点击