File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ /*
3
+ 15. 3Sum
4
+ solution C++
5
+ O(N-square)
6
+ */
7
+
8
+
9
+ class Solution {
10
+ public:
11
+ vector<vector<int >> threeSum (vector<int >& nums) {
12
+ set<vector<int >> ans;
13
+ int n= nums.size ();
14
+ if (n <3 )
15
+ return {};
16
+
17
+ sort (nums.begin (), nums.end ()); // for using two pointers technique
18
+
19
+ for (int i=0 ; i<n-2 ; i++){
20
+ // now using two pointers to find the second and third
21
+
22
+ if (i >0 && nums[i] == nums[i-1 ])
23
+ continue ;
24
+ int start = i+1 , end= n-1 ;
25
+ while (start < end){
26
+ int sum = nums[i] + nums[start]+ nums[end];
27
+ if (sum == 0 )
28
+ { ans.insert ({nums[i],nums[start], nums[end]}); start +=1 ;}
29
+
30
+ else if (sum > 0 )
31
+ end -=1 ;
32
+ else
33
+ start +=1 ;
34
+
35
+ }
36
+ }
37
+
38
+ vector<vector<int >> yo;
39
+ for (auto i= ans.begin (); i != ans.end (); i++)
40
+ yo.push_back (*i);
41
+ return yo;
42
+ }
43
+ };
You can’t perform that action at this time.
0 commit comments