码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – 3sum

时间:2015-03-18 07:46:33      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

For this problem, do not forget to skip the duplicates for i. Usually I will do duplication removal for j and k.

Tag it.

 

 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int> &num) {
 4         vector<vector<int> > result;
 5         int len = num.size(), i = 0, j = 0, k = 0;
 6         if (len < 2) return result;
 7         sort(num.begin(), num.end());
 8         for (int i = 0; i < len-2; i++) {
 9             if (i > 0 && num[i] == num[i-1]) continue;
10             j = i+1, k = len-1;
11             while (j < k) {
12                 int sum = num[i] + num[j] + num[k];
13                 if (sum > 0) k--;
14                 else if (sum < 0) j++;
15                 else {
16                     vector<int> tmp;
17                     tmp.push_back(num[i]);
18                     tmp.push_back(num[j]);
19                     tmp.push_back(num[k]);
20                     result.push_back(tmp);
21                     do{j++;} while (j < k && num[j] == num[j-1]);
22                     do{k--;} while (j < k && num[k] == num[k+1]);
23                 }
24             }
25         }
26         return result;
27     }
28 };

 

LeetCode – Refresh – 3sum

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4346149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!