-
Notifications
You must be signed in to change notification settings - Fork 564
Expand file tree
/
Copy path27. 3Sum Closest.cpp
More file actions
40 lines (33 loc) · 1.02 KB
/
27. 3Sum Closest.cpp
File metadata and controls
40 lines (33 loc) · 1.02 KB
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
40
/*
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.
Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Constraints:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
*/
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int ans = INT_MIN, diff = INT_MAX;
sort(nums.begin(), nums.end());
for(int i = 0; i < nums.size(); ++i) {
int j = i+1, k = nums.size()-1;
while(j < k) {
int val = nums[i] + nums[j] + nums[k];
if(abs(target - val) < diff) {
ans = val;
diff = abs(target - val);
}
if(val < target) j++;
else k--;
}
}
return ans;
}
};