|
| 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