Skip to content

Commit 02645c8

Browse files
committed
Solution: Longest Consecutive Sequence
1 parent c40ce20 commit 02645c8

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* ํ’€์ด
3+
* - ์ฃผ์–ด์ง„ ๋ฐฐ์—ด `nums`๋กœ set `s`๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค
4+
* - `nums`๋ฅผ ์กฐํšŒํ•˜๋Š”๋ฐ, ํ˜„์žฌ ์กฐํšŒ ์ค‘์ธ `num`์— ๋Œ€ํ•˜์—ฌ `num - 1`์ด `s`์— ํฌํ•จ๋˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋งŒ while๋ฌธ์„ ์‹คํ–‰ํ•˜์—ฌ subsequence์˜ ๊ธธ์ด๋ฅผ ์ธก์ •ํ•ฉ๋‹ˆ๋‹ค
5+
* - `num - 1`์ด `s`์— ํฌํ•จ๋˜์ง€ ์•Š๋Š”๋‹ค๋Š” ๊ฒƒ์€ `num`์ด ํ•ด๋‹น subsequence์˜ ์ฒซ ์ˆ˜์ž„์„ ๋œปํ•ฉ๋‹ˆ๋‹ค
6+
*
7+
* Big-O
8+
* - N: ์ฃผ์–ด์ง„ ๋ฐฐ์—ด `nums`์˜ ๊ธธ์ด
9+
*
10+
* - Time complexity: O(N)
11+
* - ์ด์ค‘ ๋ฐ˜๋ณต๋ฌธ์˜ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์กŒ์ง€๋งŒ, ์กฐ๊ฑด๋ฌธ๋•Œ๋ฌธ์— ๊ฐ ์›์†Œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ๋งŒ ์กฐํšŒํ•ฉ๋‹ˆ๋‹ค
12+
*
13+
* - Space complexity: O(N)
14+
* - `nums`๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ์›์†Œ๊ฐ€ ๋ชจ๋‘ ๊ณ ์œ ํ•œ ์ •์ˆ˜์ผ ๊ฒฝ์šฐ, `s`์˜ ํฌ๊ธฐ๊ฐ€ `nums`๋งŒํผ ์ปค์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
15+
*/
16+
17+
class Solution {
18+
public:
19+
int longestConsecutive(vector<int>& nums) {
20+
unordered_set<int> s(nums.begin(), nums.end());
21+
22+
int res = 0;
23+
for (int num : nums) {
24+
if (s.find(num - 1) != s.end()) continue;
25+
26+
int curr = num;
27+
int streak = 1;
28+
while (s.find(curr + 1) != s.end()) {
29+
++curr;
30+
++streak;
31+
}
32+
res = max(res, streak);
33+
}
34+
35+
return res;
36+
}
37+
};

0 commit comments

Comments
ย (0)