Created
July 7, 2013 08:09
-
-
Save luoxiaoxun/5942761 to your computer and use it in GitHub Desktop.
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| C++: | |
| class Solution { | |
| public: | |
| int threeSumClosest(vector<int> &num, int target) { | |
| // Start typing your C/C++ solution below | |
| // DO NOT write int main() function | |
| int ret; | |
| int temp=INT_MAX; | |
| sort(num.begin(),num.end()); | |
| for(int i=0;i<num.size()-2;i++){ | |
| int j=i+1; | |
| int k=num.size()-1; | |
| while(j<k){ | |
| int sum=num[i]+num[j]+num[k]; | |
| if(abs(sum-target)<temp){ | |
| ret=sum; | |
| temp=abs(sum-target); | |
| } | |
| if(sum>target) k--; | |
| else j++; | |
| } | |
| } | |
| return ret; | |
| } | |
| }; | |
| Java: | |
| public class Solution { | |
| public int threeSumClosest(int[] num, int target) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| int ret=0; | |
| int temp=Integer.MAX_VALUE; | |
| Arrays.sort(num); | |
| for(int i=0;i<num.length-2;i++){ | |
| int j=i+1; | |
| int k=num.length-1; | |
| while(j<k){ | |
| int sum=num[i]+num[j]+num[k]; | |
| if(Math.abs(sum-target)<temp){ | |
| ret=sum; | |
| temp=Math.abs(sum-target); | |
| } | |
| if(sum>target) k--; | |
| else j++; | |
| } | |
| } | |
| return ret; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment