File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You canโt perform that action at this time.
0 commit comments