3Sum Jan 18 '12 8685 / 33750
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ? b ? c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { sort(num.begin(), num.end()); vector<vector<int> > res; int len = num.size(); for (int i = 0; i < len - 2; i++) { if (i > 0 && num[i] == num[i-1]) continue; int a = i+1, b = len -1; int t = -num[i]; while (a < b) { if (num[a] + num[b] == t) { int tmp[3] = {-t, num[a], num[b]}; vector<int> tmp2(tmp, tmp+3); res.push_back(std::move(tmp2)); while (a < b && num[a] == num[a+1]) a++; a++; while (a < b && num[b] == num[b-1]) b--; b--; } else if (num[a] + num[b] > t) { b--; } else a++; } } return res; } };
3Sum Closest
Jan 18 '12
5336 / 13935
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).» Solve this problem
class Solution { public: int threeSumClosest(vector<int> &num, int target) { sort(num.begin(), num.end()); int len = num.size(); int mindelta = 1 << 30; int res; for (int i = 0; i < len - 2; i++) { if (i > 0 && num[i] == num[i-1]) continue; int a = i+1, b = len -1; int t = target - num[i]; while (a < b) { int delta = t - num[a] - num[b]; if (delta == 0) return target; else if (delta > 0) { if (delta < mindelta) mindelta = delta, res = target - delta; a++; } else { if (-delta < mindelta) mindelta = -delta, res = target- delta; b--; } } } return res; } };
扫描二维码关注公众号,回复:
1240284 查看本文章