forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
3Sum Closest.cpp
39 lines (38 loc) · 1.16 KB
/
3Sum Closest.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int sum = INT_MAX;
int difference = INT_MAX;
for(int index = 0; index < nums.size()-2; index++)
{
if (index == 0 || nums[index - 1] != nums[index])
{
generateSumValues(index, target, sum, difference, nums);
if(sum == target)
return sum;
}
}
return sum;
}
void generateSumValues(int index, int target, int& sum, int& difference, const vector<int>& nums)
{
int low = index+1, hi = nums.size()-1;
while(low < hi)
{
int tempSum = nums[index] + nums[low] + nums[hi];
int tempDifference = target - tempSum;
int absDifference = abs(tempDifference);
if(absDifference < difference)
{
difference = absDifference;
sum = tempSum;
}
if(tempSum < target)
low++;
else if(tempSum > target)
hi--;
else return;
}
}
};