Fast accepted cpp solution


  • 0
    T
    int threeSumClosest(vector<int> &num, int target) {
            sort(num.begin(), num.end());
            const int N = num.size();
            int minDis = INT_MAX;
            int result = 0;
            for(int i = 0; i < N; ++i)
            {
                if(i > 0 && num[i] == num[i-1]) continue;
                int s = i + 1, e = N -1;
                while(s < e)
                {
                    int curSum = num[s] + num[e] + num[i];
                    int curDis = abs(curSum - target);
                    if(curDis < minDis)
                    {
                        minDis = curDis;
                        result = curSum;
                    }
                    if(curSum == target)
                    {
                        return target;
                    }else if(curSum > target)
                    {
                        while(s < --e && num[e] == num[e+1]);
                    }else
                    {
                        while(++s < e && num[s] == num[s-1]);
                    }
                }
            }
            return result;
        }

Log in to reply
 

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