|
4 | 4 | class SolutionLongestConsecutiveSequence { |
5 | 5 |
|
6 | 6 | public int longestConsecutive(int[] nums) { |
7 | | - // μ λ ¬λμ§ μμ μ μ nums λ°°μ΄μ΄ μ£Όμ΄μ§λ©΄ κ°μ₯ κΈ΄ μ°μ μμ μνμ€ κΈΈμ΄λ₯Ό λ°ν |
8 | | - // O(N) μκ° λ΄ μ€νλμΌν¨ |
9 | | - // μ λΆ ν΄μλ§΅μ λλ €λ£κ³ , ν€λ₯Ό κΊΌλ΄ μ°μ μμκ° μλμ§ νμΈνλ€ |
10 | | - // μ°μ μμκ° μμΌλ©΄ answerλ₯Ό 1 μ¦κ°μν€κ³ , μ°μ μμλ μ κ±°νλ€ |
11 | | - // μκ°λ³΅μ‘λ: O(N), 곡κ°λ³΅μ‘λ: O(N) |
12 | | - |
13 | | - Set<Integer> set = new HashSet<>(); |
14 | | - for (var num : nums) { |
15 | | - set.add(num); |
16 | | - } |
17 | | - var answer = 0; |
18 | | - for (var num : nums) { |
19 | | - var length = 1; |
20 | | - |
21 | | - if (set.contains(num-1)) { |
22 | | - set.remove(num); |
23 | | - var minusKey = num; |
24 | | - while (set.contains(--minusKey)) { |
25 | | - length++; |
26 | | - set.remove(minusKey); |
27 | | - } |
| 7 | + // μνμ€ μ‘°νλ₯Ό O(1)μ μν κ°λ₯νκ³ , μ€λ³΅μ 무μν μ μλ 쑰건μ΄λ―λ‘ Setμ΄ μ ν©ν μλ£κ΅¬μ‘° |
| 8 | + // μκ°λ³΅μ‘λ: O(N), 곡κ°λ³΅μ‘λ: O(N) |
| 9 | + Set<Integer> num_set = new HashSet<Integer>(); |
| 10 | + for (int num : nums) { |
| 11 | + num_set.add(num); |
28 | 12 | } |
29 | 13 |
|
30 | | - if (set.contains(num+1)) { |
31 | | - set.remove(num); |
32 | | - var plusKey = num; |
33 | | - while (set.contains(++plusKey)) { |
34 | | - length++; |
35 | | - set.remove(plusKey); |
36 | | - } |
37 | | - } |
| 14 | + int longestSequence = 0; |
| 15 | + |
| 16 | + // μκ°λ³΅μ‘λ: O(N) |
| 17 | + for (int num : num_set) { |
| 18 | + // μνμ€ μ€κ°μ μλ μ«μκ° μλ μμνλ μ«μλ₯Ό μ°Ύμ |
| 19 | + // μμνλ μ«μλ - 1 κ°μ΄ Setμ μμ κ² |
| 20 | + if (!num_set.contains(num - 1)) { |
| 21 | + int currentNum = num; |
| 22 | + int currentLength = 1; |
| 23 | + // + 1 κ°μ΄ Setμ μλ μ§ νμΈνλ©΄μ μ¦κ° |
| 24 | + while (num_set.contains(currentNum + 1)) { |
| 25 | + currentNum += 1; |
| 26 | + currentLength += 1; |
| 27 | + } |
38 | 28 |
|
39 | | - if (length > answer) { |
40 | | - answer = length; |
| 29 | + // μνκ° λλλ©΄ μ΅λ μνμ€ κΈΈμ΄μΈμ§ νμΈνκ³ μ μ© |
| 30 | + longestSequence = Math.max(longestSequence, currentLength); |
| 31 | + } |
41 | 32 | } |
42 | | - } |
43 | 33 |
|
44 | | - return answer; |
| 34 | + return longestSequence; |
45 | 35 | } |
46 | 36 | } |
0 commit comments