forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflynn.cpp
37 lines (33 loc) ยท 1.21 KB
/
flynn.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
/**
* ํ์ด
* - ์ฃผ์ด์ง ๋ฐฐ์ด `nums`๋ก set `s`๋ฅผ ๋ง๋ญ๋๋ค
* - `nums`๋ฅผ ์กฐํํ๋๋ฐ, ํ์ฌ ์กฐํ ์ค์ธ `num`์ ๋ํ์ฌ `num - 1`์ด `s`์ ํฌํจ๋์ง ์๋ ๊ฒฝ์ฐ๋ง while๋ฌธ์ ์คํํ์ฌ subsequence์ ๊ธธ์ด๋ฅผ ์ธก์ ํฉ๋๋ค
* - `num - 1`์ด `s`์ ํฌํจ๋์ง ์๋๋ค๋ ๊ฒ์ `num`์ด ํด๋น subsequence์ ์ฒซ ์์์ ๋ปํฉ๋๋ค
*
* Big-O
* - N: ์ฃผ์ด์ง ๋ฐฐ์ด `nums`์ ๊ธธ์ด
*
* - Time complexity: O(N)
* - ์ด์ค ๋ฐ๋ณต๋ฌธ์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ก์ง๋ง, ์กฐ๊ฑด๋ฌธ๋๋ฌธ์ ๊ฐ ์์๋ฅผ ํ ๋ฒ์ฉ๋ง ์กฐํํฉ๋๋ค
*
* - Space complexity: O(N)
* - `nums`๋ฅผ ๊ตฌ์ฑํ๋ ์์๊ฐ ๋ชจ๋ ๊ณ ์ ํ ์ ์์ผ ๊ฒฝ์ฐ, `s`์ ํฌ๊ธฐ๊ฐ `nums`๋งํผ ์ปค์ง ์ ์์ต๋๋ค
*/
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
int res = 0;
for (int num : nums) {
if (s.find(num - 1) != s.end()) continue;
int curr = num;
int streak = 1;
while (s.find(curr + 1) != s.end()) {
++curr;
++streak;
}
res = max(res, streak);
}
return res;
}
};