[LeetCode] 3Sum-Closest

16. 3Sum Closest

Given an array nums of n integers 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.

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
class Solution {
private:
int getSum(vector<int> &nums, int p1, int p2, int p3) {
return nums[p1] + nums[p2] + nums[p3];
}

int getAnswer(int num, int target, int compare) {
return abs(num - target) >= abs(compare - target) ? compare : num;
}

public:
int threeSumClosest(vector<int> &nums, int target) {
sort(nums.begin(), nums.end());

int p1 = 0, p2 = 1, p3 = nums.size() - 1;
int answer = getSum(nums, p1, p2, p3), comp;

for (p1 = 0; p1 < nums.size() - 2 && nums[p1] * 3 <= target; p1++) {
p2 = p1 + 1;
p3 = nums.size() - 1;

while (p2 < p3) {
comp = getSum(nums, p1, p2, p3);
answer = getAnswer(answer, target, comp);
if (comp >= target)
p3--;
else
p2++;
}
}

return answer;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/13/PS/LeetCode/3sum-closest/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.