Skip to content

Commit 5fcd582

Browse files
author
easyone
committed
Feat: Add solution of longest-consecutive-sequence.
1 parent 9bfe355 commit 5fcd582

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// 풀이
2+
// You must write an algorithm that runs in O(n) time.
3+
// TCλ₯Ό O(n) μ΄λ‚΄λ‘œ ν•΄μ•Όν•œλ‹€λŠ” 것은 sortλ₯Ό μ“°μ§€ λ§λΌλŠ” 의미.
4+
// map을 μ‚¬μš©ν•˜κ³  μˆœνšŒν•˜λ©° 연속이 μ‹œμž‘λ˜λŠ” 값을 μ°Ύκ³  찾으면 μ—°μ†λ˜λŠ”μ§€ μ°ΎκΈ°.
5+
6+
// TC
7+
// μˆœνšŒν•˜λŠ” mapμ•ˆμ—μ„œ for문을 또 ν˜ΈμΆœν•˜κΈ΄ ν•˜μ§€λ§Œ,
8+
// λͺ¨λ“  값이 μ—°μ†λ˜λŠ” 값이라고 ν–ˆμ„ λ•Œ
9+
// 연속이 μ‹œμž‘λ˜λŠ” κ°’ μ™Έμ—λŠ” ν•œ λ²ˆμ”© λ°”λ‘œ μ§€λ‚˜κ°€κ²Œ 되고(n*1), μ‹œμž‘λ˜λŠ” κ°’λΆ€ν„° 연속이 λλ‚˜λŠ” μ‹œμ κΉŒμ§€ n번이라(1*n)
10+
// O(n+n) 이기 λ•Œλ¬Έμ— TCλŠ” O(n)
11+
12+
// SC
13+
// map이 μ΅œλŒ€λ‘œ μ°¨μ§€ν•˜λŠ” 곡간은 O(n)
14+
15+
func longestConsecutive(nums []int) int {
16+
m := make(map[int]bool)
17+
for _, num := range nums {
18+
m[num] = true
19+
}
20+
length := 1
21+
maxLength := 0
22+
for k := range m {
23+
if _, ok := m[k-1]; !ok {
24+
i := 1
25+
for {
26+
if _, ok := m[k+i]; ok {
27+
length++
28+
i++
29+
} else {
30+
break
31+
}
32+
}
33+
if maxLength < length {
34+
maxLength = length
35+
}
36+
length = 1
37+
}
38+
}
39+
return maxLength
40+
}

0 commit comments

Comments
Β (0)