forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
83 lines (62 loc) · 2.05 KB
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/// Source : https://leetcode.com/problems/3sum/
/// Author : liuyubobobo
/// Time : 2016-12-03
#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>
using namespace std;
/// Using two pointer technique
/// Time Complexity: O(n^2)
/// Space Complexity: O(n)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
int index = 0;
while( index < nums.size() ){
if( nums[index] > 0 )
break;
int bindex = index + 1;
int cindex = nums.size()-1;
while( bindex < cindex) {
if (nums[bindex] + nums[cindex] == -nums[index]) {
res.push_back({nums[index], nums[bindex], nums[cindex]});
// continue to look for other pairs
bindex = next_num_index( nums, bindex );
cindex = pre_num_index( nums, cindex);
}
else if (nums[bindex] + nums[cindex] < -nums[index])
bindex = next_num_index( nums, bindex );
else //nums[bindex] + nums[cindex] > -nums[index]
cindex = pre_num_index( nums, cindex);
}
index = next_num_index( nums , index );
}
return res;
}
private:
int next_num_index( const vector<int> &nums, int cur ){
for( int i = cur + 1; i < nums.size() ; i ++ )
if( nums[i] != nums[cur] )
return i;
return nums.size();
}
int pre_num_index( const vector<int> &nums, int cur){
for( int i = cur - 1; i >= 0 ; i -- )
if( nums[i] != nums[cur] )
return i;
return -1;
}
};
int main() {
vector<int> nums1 = {-1, 0, 1, 2, -1, -4};
vector<vector<int>> res = Solution().threeSum(nums1);
for( int i = 0 ; i < res.size() ; i ++ ){
for( int j = 0 ; j < res[i].size() ; j ++ )
cout<<res[i][j]<<" ";
cout<<endl;
}
return 0;
}