3 Sum Closest(c++,n^2)


  • 0
    Z

    class Solution {
    public:
    int threeSumClosest(vector<int>& nums, int target) {
    sort(nums.begin(), nums.end());
    int result = nums[0] + nums[1] + nums[2]; //initialize
    for (int i = 0; i < nums.size() - 2; i++){
    if (i > 0 && nums[i] == nums[i - 1]) continue; //if occurs the same number, continue
    int k = i + 1, j = nums.size() - 1;
    while(k < j){
    if (abs(nums[i] + nums[k] + nums[j] - target) < abs(result - target)) result = nums[i] + nums[k] + nums[j];
    if (nums[i] + nums[k] + nums[j] > target) j--;
    else if (nums[i] + nums[k] + nums[j] < target) k++;
    else return target;
    }
    }
    return result;
    }
    };


Log in to reply
 

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