Skip to content

Commit 8fd6e1f

Browse files
committed
longest consecutive sequence solution
1 parent b30a901 commit 8fd6e1f

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+
time: O(N), space: O(N)
4+
- ์ค‘๋ณต ์ œ๊ฑฐ
5+
- ์—ฐ์†๋œ ํšŸ์ˆ˜ max ๊ตฌํ•˜๊ธฐ
6+
-- ์—ฐ์†๋œ ์ˆซ์ž ๊ทธ๋ฃน ์ค‘ ์ฒซ๋ฒˆ์งธ๋ถ€ํ„ฐ ์‹œ์ž‘๋˜๋„๋ก
7+
8+
[ํšŒ๊ณ ]
9+
์—ฐ์†๋œ ์ˆซ์ž ๊ทธ๋ฃน ์ค‘ ์ฒซ๋ฒˆ์งธ๋ถ€ํ„ฐ ์‹œ์ž‘๋˜๋„๋ก ํ•˜๋Š” ๋ถ€๋ถ„์—์„œ ๋ง‰ํ˜”๋‹ค..
10+
์ฐจ๋ถ„ํžˆ ์ƒ๊ฐํ•ด๋ณด๋ฉด ๋ฌด๋ฆฌ์—†์ด ํ’€ ์ˆ˜ ์žˆ์ง€ ์•Š์•˜์„๊นŒ..
11+
*/
12+
class Solution {
13+
public int longestConsecutive(int[] nums) {
14+
if (nums.length == 0) {
15+
return 0;
16+
}
17+
18+
Set<Integer> numsSet = new HashSet<>();
19+
for (int num : nums) {
20+
numsSet.add(num);
21+
}
22+
23+
int maxCount = 1;
24+
for (int num : numsSet) {
25+
if (!numsSet.contains(num - 1)) {
26+
int count = 1;
27+
int currentNum = num;
28+
while (numsSet.contains(currentNum + 1)) {
29+
count++;
30+
currentNum++;
31+
}
32+
maxCount = Math.max(maxCount, count);
33+
}
34+
}
35+
return maxCount;
36+
}
37+
}

0 commit comments

Comments
ย (0)