LeetCode 16. 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution

Two Pointers

int threeSumClosest(vector<int>& nums, int target) {
  if (nums.size() < 3) {
    return accumulate(nums.begin(), nums.end(), 0);
  }

  sort(nums.begin(), nums.end());

  int closest = nums[0] + nums[1] + nums[2];
  for (int left = 0 ; left < nums.size() - 2 ; ++left) {
    // Skip the duplicate left values.
    if (left > 0 && nums[left] == nums[left - 1]) {
      continue;
    }

    int middle = left + 1;
    int right = nums.size() - 1;
    while(middle < right) {
      int sum = nums[left] + nums[middle] + nums[right];

      if (target == sum) {
        return sum;
      }

      if (abs(target - sum) < abs(target - closest)) {
        closest = sum;
      }

      sum < target ? ++middle : --right;
    }
  }

  return closest;
}

results matching ""

    No results matching ""