[leetcode] 3Sum Closest

3Sum Closest

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int res;
        int minGap=INT_MAX;
        sort(num.begin(),num.end());//排序
        
        for(int i=0;i<num.size();i++){
            if(i>0&&num[i]==num[i-1]){//过滤重复
                continue;
            }
            int j=i+1;
            int k=num.size()-1;
            
            while(j<k){//左右夹逼
                if(j>i+1&&num[j]==num[j-1]){//过滤重复
                    j++;
                    continue;
                }
                if(k<num.size()-1&&num[k]==num[k+1]){//过滤重复
                    k--;
                    continue;
                }
                int sum=num[i]+num[j]+num[k];
                
                if(abs(sum-target)<minGap){//更新最小值
                    minGap=abs(sum-target);
                    res=sum;
                }
                if(sum>target){
                    k--;
                }else{
                    j++;
                }
            }
            
        }
        return res;
    }
};


你可能感兴趣的:([leetcode] 3Sum Closest)