LeetCode15_三数之和

这个题解超时了,mark一下后面再改

 1 #include <iostream>
 2 #include <algorithm>
 3 
 4 
 5 using namespace std;
 6 
 7 /***
 8  *
 9  *  给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
10  *  注意:答案中不可以包含重复的三元组。
11 
12     给定数组 nums = [-1, 0, 1, 2, -1, -4],
13 
14     满足要求的三元组集合为:
15     [
16       [-1, 0, 1],
17       [-1, -1, 2]
18     ]
19 
20 
21     // 去重问题:有序性保证了相等数的相邻性;如果某数等于其上一个位置的数值时,便不作为新的结果;->所以排序使得去重变得方便了;
22     // 有序性还可以使得使用双指针的方式来遍历成为可能,能遍历所有可能,且这样的遍历更加高效;
23  */
24 
25 
26 class Solution {
27 public:
28     vector<vector<int>> threeSum(vector<int>& nums) {
29         vector<vector<int>> res;
30         if(nums.size()<3)
31             return res;
32 
33         sort(nums.begin(),nums.end());
34         for(int i =0; i<nums.size()-2;i++){
35             if(nums[i]>0){  //后面所有数都会大于0
36                 return res;
37             }
38             if(i>0 && nums[i]==nums[i-1])
39                 continue;
40             int pL = i+1, pR = nums.size()-1;  //左指针,右指针
41             while(pL<pR){
42                 int total = nums[i]+nums[pL]+nums[pR];
43                 if(total<0){
44                     pL++;
45                 }
46                 else if(total > 0){
47                     pR--;
48                 }
49                 else{
50                     vector<int> temp = {nums[i],nums[pL],nums[pR]};
51                     res.push_back(temp);
52                     //去重
53                     while(pL<pR && nums[pL]==nums[pL+1]){
54                         pL++;
55                     }
56                     while(pL<pR && nums[pR]==nums[pR-1]){
57                         pR--;
58                     }
59                 }
60             }
61         }
62 
63         return res;
64     }
65 };

 

posted @ 2020-02-25 11:29  Grooovvve  阅读(138)  评论(0编辑  收藏  举报