Three Sum Closest
#include <bits/stdc++.h>
using namespace std;
// https://leetcode.com/problems/3sum-closest/
// Given an integer array nums of length n and
// an integer target, find three integers in nums
// such that the sum is closest to target.
// Return the sum of the three integers.
// You may assume that each input would have
// exactly one solution.
int threeSumClosest(vector<int> &nums, int target){
// observations:
// 1. initialize a variable sum = first three element sum and a variable diff = abs(target - sum).
// 2. using a for loop & while loop, fix a variable and apply two pointer technique on rest of the search space (from i+1 to n-1).
// 3. Inside while loop, keep checking if abs(curSum - target) < diff then update diff and sum = curSum.
// 4. keep repeating step 3 along with two pointer till end of for loop.
// NOTE: take abs() on each step while taking differences so that there can not be any confusional cases.
int sum = nums[0] + nums[1] + nums[2];
int diff = abs(sum - target);
sort(nums.begin(), nums.end());
for(int i=0;i<nums.size()-2;i++){
int p = i+1;
int q = nums.size()-1;
while(p < q){
int curSum = nums[i] + nums[p] + nums[q];
int curDiff = abs(curSum - target);
//update diff and curSum if curdiff is smaller:
if(curDiff < diff){
sum = curSum;
diff = curDiff;
}
if(curSum == target) return target;
else if(curSum < target) p++;
else q--;
}
}
return sum;
}
void main(){
}
Comments
Post a Comment