forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrumbs22.cpp
More file actions
62 lines (52 loc) ยท 1.34 KB
/
crumbs22.cpp
File metadata and controls
62 lines (52 loc) ยท 1.34 KB
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
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
/*
TC: O(n^2)
- sort: O(nlogn)
- ๋ฐ๊นฅ๋ฃจํ * ์์ชฝ๋ฃจํ: O(n^2)
SC: O(1)
ํ์ด ๋ฐฉ๋ฒ:
- nums ๋ฐฐ์ด์ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ
- ์ฒซ๋ฒ์งธ ์ซ์๋ฅผ ๊ธฐ์ค์ผ๋ก, ๋๋จธ์ง ๋ ์ซ์๋ ํฌ ํฌ์ธํฐ๋ก ํ์
- ์ธ ์์ ํฉ์ด 0์ด๋ฉด ans์ ์ถ๊ฐ
- ์ค๋ณต๋๋ ๊ฐ๋ค์ ๊ฑด๋๋ฐ๋ฉด์ ans๋ฐฐ์ด์ ์ค๋ณต๋๋ ๋ฒกํฐ๊ฐ ๋ค์ด๊ฐ์ง ์๋๋ก ํ๋ค
*/
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
for (int idx = 0; idx < nums.size() - 2; idx++)
{
// ์ค๋ณต๋๋ ์ซ์ ๊ฑด๋๋ฐ๊ธฐ
if (idx > 0 && nums[idx] == nums[idx - 1])
continue ;
int left = idx + 1;
int right = nums.size() - 1;
while (left < right)
{
int sum = nums[idx] + nums[left] + nums[right];
if (sum < 0)
left++;
else if (sum > 0)
right--;
else
{
// ํฉ์ด 0์ธ ๊ฒฝ์ฐ ๋ฒกํฐ ans์ ์ฝ์
ans.push_back({nums[idx], nums[right], nums[left]});
// ์ค๋ณต๋๋ ์ซ์ ๊ฑด๋๋ฐ๊ธฐ
while (left < right && nums[left] == nums[left + 1])
left++;
while (left < right && nums[right] == nums[right - 1])
right--;
left++;
right--;
}
}
}
return (ans);
}
};