【数组】15. 三数之和

题目:

 

 

解答:

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

 

posted @ 2020-05-04 19:25  梦醒潇湘  阅读(193)  评论(0)    收藏  举报