Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d18aaea

Browse files
Merge pull request #109 from theneek14/master
Create 3sum_closest.cpp
2 parents 954c140 + ee265db commit d18aaea

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎03-Arrays/3sum_closest.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
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.
3+
Return the sum of the three integers.
4+
Leetcode Problem Link: https://leetcode.com/problems/3sum-closest/
5+
My Leetcode Profile: theneek14
6+
*/
7+
8+
//C++ Implementation
9+
//My Original Code
10+
#include <bits/stdc++.h>
11+
using namespace std;
12+
13+
int threeSumClosest(vector<int>& a, int t) {
14+
sort(a.begin(),a.end());
15+
int n=a.size(), ans, d=INT_MAX;
16+
for(int i=0; i<n; i++){
17+
int l=i+1, r=n-1;
18+
while(r>l){
19+
int x=a[l]+a[i]+a[r];
20+
if(d>abs(x-t)) {d=abs(x-t); ans=x;}
21+
if(x==t) return x;
22+
if(x>t) r--;
23+
if(x<t) l++;
24+
}
25+
}
26+
return ans;
27+
}
28+
29+
int main(){
30+
//size of array
31+
int n; cin>>n;
32+
33+
vector<int> nums(n); //array of elements
34+
35+
for(int i=0; i<n; i++){cin>>nums[i];}
36+
37+
int target; cin>>target;
38+
39+
cout<<"The sum of 3 integers, closest to target is: "<<threeSumClosest(nums, target);
40+
41+
return 0;
42+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /