leetcode--3Sum Closest
2013-08-22 18:17
253 查看
1.题目描述
2.解法分析
关于这个题目的解法一个共识就是需要排序,由于有三个数需要考虑,最简单的办法自然事件复杂度为O(N3),所以排序的复杂度可以忽略,排完序之后,可以得到一个O(N2)的算法。
[/code]
[code]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). [/code] |
2.解法分析
关于这个题目的解法一个共识就是需要排序,由于有三个数需要考虑,最简单的办法自然事件复杂度为O(N3),所以排序的复杂度可以忽略,排完序之后,可以得到一个O(N2)的算法。
[code]class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int numSize = num.size();
if(numSize<3)return -1;
sort(num.begin(),num.end());
int minMargin=num[0]+num[1]+num[2]-target;
int curMargin=0;
for(int i=0;i<=numSize-3;++i)
{
int j;int k;
for(j=i+1,k=numSize-1;j<k;)
{
curMargin=num[i]+num[j]+num[k]-target;
if(curMargin==0)return target;
if(abs(curMargin)<abs(minMargin))minMargin=curMargin;
if(curMargin<0)j++;
else k--;
}
}
return minMargin+target;
}
};
[/code]
相关文章推荐
- LeetCode:3Sum Closest
- Leetcode: 3Sum Closest
- LeetCode16 3Sum Closest
- leetcode(2)3sum-closest
- LeetCode:3Sum Closest
- leetcode16 3Sum Closest
- [Leetcode]3Sum Closest
- leetcode 16. 3Sum Closest
- [LeetCode]3Sum Closest
- leetcode(M) 3sum closest
- [leetcode] 3Sum Closest
- [LeetCode] 3Sum Closest
- Leetcode 1. Two Sum & 15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- leetcode: 3SumClosest
- LeetCode 16. 3Sum Closest
- C#解leetcode 16. 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode 16. 3Sum Closest
- LeetCode --- 16. 3Sum Closest
- LeetCode-3Sum Closest