LintCode: 3 Sum
C++
把3个数求和,转变为2个数求和
1. 把数组排序
2. 注意过滤重复值
3. 从前到后遍历,游标i
4. 从后边数中找start + end = -arr[i]的2 sum
5. start + end < -arr[i], start++
6. start + end > -arr[i], end--
7. start + end = -arr[i], insert <i, start, end> into result vecotr
1 class Solution { 2 public: 3 /** 4 * @param numbers : Give an array numbers of n integer 5 * @return : Find all unique triplets in the array which gives the sum of zero. 6 */ 7 vector<vector<int> > threeSum(vector<int> &nums) { 8 // write your code here 9 vector<vector<int> > result; 10 11 sort(nums.begin(), nums.end()); 12 for (int i = 0; i < nums.size(); i++) { 13 if (i > 0 && nums[i] == nums[i - 1]) { 14 continue; 15 } 16 // two sum; 17 int start = i + 1, end = nums.size() - 1; 18 int target = -nums[i]; 19 while (start < end) { 20 if (start > i + 1 && nums[start - 1] == nums[start]) { 21 start++; 22 continue; 23 } 24 if (nums[start] + nums[end] < target) { 25 start++; 26 } else if (nums[start] + nums[end] > target) { 27 end--; 28 } else { 29 vector<int> triple; 30 triple.push_back(nums[i]); 31 triple.push_back(nums[start]); 32 triple.push_back(nums[end]); 33 result.push_back(triple); 34 start++; 35 } 36 } 37 } 38 39 return result; 40 } 41 };
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。