【LeetCode】3Sum Closest
2014-04-16 22:50
302 查看
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.
思路:同3sum,不再赘述。
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).
思路:同3sum,不再赘述。
class Solution { public: int Absolute_value(int x){ if(x<0)return -x; return x; } int threeSumClosest(vector<int> &num, int target){ int nsize=num.size(),sum=0; if(nsize<3){ for(nsize--;nsize>=0;nsize--)sum+=num[nsize]; return sum; } sum=num[0]+num[1]+num[2]; sort(num.begin(),num.end()); int i,j,k=nsize-1,tmp; for(i=0;i<nsize-2;i++){ if(i > 0 && num[i]==num[i-1]) continue; j=i+1; k=nsize-1; for(;j<k;){ tmp=num[j]+num[k]+num[i]; if(Absolute_value(sum-target)>Absolute_value(tmp-target))sum=tmp; if(j>i+1&&num[j]==num[j-1]){ j++; continue; } if(k<num.size()-1&& num[k]==num[k+1]){ k--; continue; } if(num[j]+num[k]+num[i]>target)k--; else if(num[j]+num[k]+num[i]<target)j++; if(sum==target)return sum; } } return sum; } };
相关文章推荐
- leetcode 16 3Sum Closest
- LeetCode 16 3Sum Closest
- leetcode 3Sum Closest
- LeetCode 16. 3Sum Closest
- 【Leetcode】之3Sum Closest
- LeetCode16——3Sum Closest
- leetcode--3Sum Closest
- 【LeetCode】3Sum Closest
- [LeetCode] 16. 3Sum Closest
- LeetCode_3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode 3Sum Closest
- LeetCode 16. 3Sum Closest
- leetcode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode:16. 3Sum Closest
- LeetCode -- 3Sum Closest
- Leetcode 16. 3Sum Closest
- LeetCode 16 3Sum Closest
- LeetCode-16-3Sum-Closest 贪心