Skip to content

Commit 3b841e0

Browse files
committed
longest consecutive sequence
1 parent 654512d commit 3b841e0

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Runtime: 26ms
3+
* Time Complexity: O(n)
4+
* - HashSet ꡬ성: O(n)
5+
* - λͺ¨λ“  μ›μ†Œ 순회: μ΅œμ•… O(n), ν‰κ· μ μœΌλ‘œ 더 빠름 (μ‘°κΈ° μ’…λ£Œ)
6+
* - 연속 μˆ˜μ—΄ 탐색: O(n)
7+
*
8+
* Memory: 95.11MB
9+
* Space Complexity: O(n)
10+
*
11+
* Approach: HashSet을 μ΄μš©ν•˜μ—¬ 쀑볡 제거 ν›„ 연속 μˆ˜μ—΄ 길이 탐색
12+
* - 연속 μˆ˜μ—΄μ˜ μ‹œμž‘μ λ§Œ νƒμƒ‰ν•˜μ—¬ 쀑볡 μž‘μ—… λ°©μ§€ (num-1이 μ—†λŠ” 경우)
13+
* - 각 μ‹œμž‘μ μ—μ„œ μ—°μ†λœ λ‹€μŒ μˆ«μžλ“€μ„ 순차적으둜 탐색
14+
* - nums μ‚¬μ΄μ¦ˆμ— 도달 μ‹œ μ‘°κΈ° μ’…λ£Œν•˜μ—¬ λΆˆν•„μš”ν•œ 탐색 λ°©μ§€
15+
*/
16+
class Solution {
17+
public int longestConsecutive(int[] nums) {
18+
if (nums.length == 0) return 0;
19+
20+
Set<Integer> set = new HashSet<>();
21+
for (int num: nums) {
22+
set.add(num);
23+
}
24+
25+
int longestLength = 0;
26+
for (int num: set) {
27+
if (!set.contains(num-1)) {
28+
int currentNum = num;
29+
int currentLength = 1;
30+
31+
while (set.contains(currentNum+1)) {
32+
currentNum++;
33+
currentLength++;
34+
}
35+
36+
longestLength = longestLength < currentLength ? currentLength : longestLength;
37+
if (longestLength == set.size()) {
38+
return longestLength;
39+
}
40+
}
41+
}
42+
43+
return longestLength;
44+
}
45+
}

0 commit comments

Comments
Β (0)