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

LeetCode--3Sum

时间:2014-08-30 23:00:40      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   log   sp   

类似于2sum,先排序,然后从左开始遍历,计算a[i]后面的等于-a[i]的两个元素,

注意去除重复元素

 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int> &num) {
 4         vector<vector<int> > res;
 5         sort(num.begin(),num.end());
 6         int n = num.size();
 7         for(int i = 0 ; i < n-2 ; ++i){
 8             if(i > 0 && (num[i] == num[i-1])){
 9                 continue;
10             }
11             int target = -num[i];
12             int left = i+1;
13             int right = n-1;
14             while(left < right){
15                 if(target == num[left] + num[right]){
16                     vector<int> triplet;
17                     triplet.push_back(num[i]);
18                     triplet.push_back(num[left]);
19                     triplet.push_back(num[right]);
20                     res.push_back(triplet);
21                     left++;
22                     while((left < right) && (num[left] == num[left-1])){
23                         left++;
24                     }
25                     right--;
26                     while((right > left) && (num[right] == num[right+1])){
27                         right--;
28                     }
29                 }
30                 else if(target > num[left] + num[right]){
31                     left++;
32                     while((left < right) && (num[left] == num[left-1])){
33                         left++;
34                     }
35                 }
36                 else{
37                     right--;
38                     while((right > left) && (num[right] == num[right+1])){
39                         right--;
40                     }
41                 }
42             }
43         }
44         return res;
45     }
46 };

 

LeetCode--3Sum

标签:style   blog   color   io   ar   for   div   log   sp   

原文地址:http://www.cnblogs.com/cane/p/3947052.html

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