My C++ solution,6ms


  • 0
    W
    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            sort(nums.begin(), nums.end());
            int first = 0, second = 1, third = nums.size() - 1;
            int closestSum = nums[first] + nums[second] + nums[third];
            while (first < second && second < third) {
                if (first + 1 == second && second + 1 == third) {
                    break;
                }
                int tmp = 0;
                if (closestSum == target) {
                    return closestSum;
                }
                else if (closestSum > target) {
                    if (third - 1 != second) {
                        tmp = closestSum - nums[third--] + nums[third];
                    } else {
                        break;
                    }
    
                }
                else {
                    if (second + 1 != third) {
                        tmp = closestSum - nums[second++] + nums[second];
                        if (tmp < target) {
                            for (int i = first + 1; i < second; i++) {
                                int tmp1 = tmp - nums[first] + nums[i];
                                if (tmp1 >= target) break;
                                tmp = tmp1;
                                first = i;
                            }
                        }
                        else if (tmp == target) return tmp;
                        else {
                            for (int j = first - 1; j >= 0; j--) {
                                int tmp2 = tmp - nums[first] + nums[j];
                                tmp = tmp2;
                                first = j;
                                if (tmp2 < target) break;
                            }
                        }
                    } else if (first + 1 != second) {
                        tmp = closestSum - nums[first++] + nums[first];
                    }
    
                }
                if (abs(tmp - target) < abs(closestSum - target)) {
                    closestSum = tmp;
                }
            }
            return closestSum;
        }
    };
    

Log in to reply
 

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