forked from aman-raza/Friends_Hack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-closest
More file actions
30 lines (22 loc) · 834 Bytes
/
3-closest
File metadata and controls
30 lines (22 loc) · 834 Bytes
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
/*
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.
*/
int threeSumClosest(vector<int>& nums, int t) {
sort(nums.begin(),nums.end());
int n=nums.size();
int ans=nums[0]+nums[1]+nums[2];
for(int i=0;i<n-1;i++){
int j=i+1, k=n-1;
while(j<k){
int sum=nums[i]+nums[j]+nums[k];
if(abs(sum-t)<abs(ans-t)){
ans=sum;
};
if(sum<t) j++;
else if(sum>t)k--;
else return sum;
}
}
return ans;
}