My c++ code On*n


  • 0
    L

    class Solution {
    public:
    int threeSumClosest(vector<int>& nums, int target) {
    int n=nums.size();
    sort(nums.begin(),nums.end());
    int ans=1000000000,anw=-1;
    for(int k=2;k<n;k++){
    int i=0,j=k-1;
    int tmp=target-nums[k];
    while(i<j){
    int sum=nums[i]+nums[j];
    if(sum<tmp || (i>0 && nums[i]==nums[i-1])){
    if(abs(nums[i]+nums[j]+nums[k]-target)<ans) {
    ans=abs(nums[i]+nums[j]+nums[k]-target);
    anw=nums[i]+nums[j]+nums[k];
    }
    i++;
    } else if(sum>tmp || (j+1<k && nums[j]==nums[j+1])){
    if(abs(nums[i]+nums[j]+nums[k]-target)<ans) {
    ans=abs(nums[i]+nums[j]+nums[k]-target);
    anw=nums[i]+nums[j]+nums[k];
    }
    j--;
    } else {
    if(abs(nums[i]+nums[j]+nums[k]-target)<ans) {
    ans=abs(nums[i]+nums[j]+nums[k]-target);
    anw=nums[i]+nums[j]+nums[k];
    }
    i++;j--;
    }
    }
    }
    return anw;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.