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

LeetCode – Refresh – 4sum

时间:2015-03-18 07:47:09      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

To be honest, I dont like this problem. This is just an extra layer loop for 3sum. But two mistakes I had made…..

1. when skip j, use condition j > i+1. Because it starts from i+1. not from i.

2. Typo or my brain is gone… condition for l is num[l] == num[l+1] since l is decreasing.

 

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

 

LeetCode – Refresh – 4sum

标签:

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

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