Simple C++ Code


  • 0
    G
        int threeSumClosest(vector<int>& nums, int target) {
            if (nums.size() < 3) return 0;
            sort(nums.begin(), nums.end());
            int closest_sum;
            int diff = INT32_MAX;
            for (int i = 0; i < nums.size(); i++) {
                int j = i + 1, k = nums.size() - 1;
                while (j < k) {
                    int sum = nums[i] + nums[j] + nums[k];
                    if (abs(sum - target) < diff) {
                        diff = abs(sum - target);
                        closest_sum = sum;
                    }
                    if (nums[i] + nums[j] + nums[k] < target) j++;
                    else if (nums[i] + nums[j] + nums[k] > target) k--;
                    else break;
                }
            }
            return closest_sum;
        }
    

Log in to reply
 

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