leetcode 15. 三数之和

 

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]


 1 #include<algorithm>
 2 class Solution {
 3 public:
 4     vector<vector<int>> threeSum(vector<int>& nums) {
 5         vector<vector<int>> ans;
 6         sort(nums.begin(), nums.end());
 7         int len = nums.size();
 8         for (int i = 0; i < len - 2;){
 9             int k = len - 1;
10             for (int j = i + 1; j < k;){
11                 if(nums[j]+nums[k] == -nums[i]){
12                     vector<int> temp;
13                     temp.push_back(nums[i]);
14                     temp.push_back(nums[j]);
15                     temp.push_back(nums[k]);
16                     ans.push_back(temp);
17                     j++;
18                     k--;
19                     while(j < k && nums[j] == nums[j-1]) j++;
20                     while(j < k && nums[k] == nums[k+1]) k--;
21                 }else if(nums[j]+nums[k] > -nums[i]){
22                     k--;
23                     while(j < k && nums[k] == nums[k+1]) k--;
24                 } else if(nums[j]+nums[k] < -nums[i]){
25                     j++;
26                     while(j < k && nums[j] == nums[j-1]) j++;
27                 }
28             }
29             i++;
30             while(i < len-2 && nums[i] == nums[i-1]) i++;
31         }
32         return ans;
33     }
34 };

 

posted @ 2018-04-26 12:21  赖兴宇  阅读(315)  评论(0编辑  收藏  举报