File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ // time complexity: O(n)
2
+ // space complexity: O(n)
3
+ // 풀이
4
+ // 1. map에 nums의 모든 요소를 저장한다.
5
+ // 2. map을 순회하면서 num-1이 존재하는지 확인한다.
6
+ // 3. num-1이 존재하면 continue
7
+ // 4. num-1이 존재하지 않으면 consecutiveCount를 1로 초기화하고 num+1이 존재하는지 (연속적으로 숫자가 증가하는게 있는지) 확인한다.
8
+ // 5. num+1이 존재하면 consecutiveCount를 1 증가시키고 num을 1 증가시켜 다음 수를 찾는다.
9
+ // 6. num+1이 존재하지 않으면 현재까지의 consecutiveCount와 maxConsecutiveCount를 비교하여 maxConsecutiveCount를 갱신한다.
10
+ func longestConsecutive (nums []int ) int {
11
+ numMap := make (map [int ]bool )
12
+
13
+ for _ , num := range nums {
14
+ numMap [num ] = true
15
+ }
16
+
17
+ maxConsecutiveCount := 0
18
+
19
+ for num := range numMap {
20
+ if numMap [num - 1 ] {
21
+ continue
22
+ }
23
+ consecutiveCount := 1
24
+ for numMap [num + 1 ] {
25
+ num ++
26
+ consecutiveCount ++
27
+ }
28
+ if consecutiveCount > maxConsecutiveCount {
29
+ maxConsecutiveCount = consecutiveCount
30
+ }
31
+ }
32
+
33
+ return maxConsecutiveCount
34
+ }
You can’t perform that action at this time.
0 commit comments