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