|
| 1 | +/* |
| 2 | +sol 1. 재귀 호출 |
| 3 | +
|
| 4 | +알고리즘 문제를 오랜만에 풀어서... union-find를 떠올리긴 했으나, 구현 방법이 가물가물해서 원하는 솔루션으로 풀지 못한 것 같습니다. |
| 5 | +일단 vis, cnt 와 재귀 호출을 사용해서 union-find와 유사하게 구현하긴 했는데요 (해설을 달면서 다시 보니 이것도 union-find를 구현하는 한 방법이라고 할 수 있을듯...?), |
| 6 | +시간이 된다면 좀 더 최적화한 솔루션을 제출해보겠습니다. |
| 7 | +
|
| 8 | +Runtime: 98 ms(Beats: 35.68 %) |
| 9 | +Time Complexity: O(n) |
| 10 | +- set, vis, cnt 생성 : O(n) |
| 11 | +- set의 모든 원소를 순회하면서 checkAbove 수행 : O(n) |
| 12 | + - checkAbove(x)는 x를 1번째 원소로 하는, 증가하는 연속 수열의 길이를 반환함 |
| 13 | + - checkAbove(x)는 재귀적으로 checkAbove(x + 1)을 호출함. |
| 14 | + - checkAbove(x)는 이미 x를 방문한 적이 있거나, set 안에 x가 존재하지 않는 경우가 base case |
| 15 | + - 따라서 set의 모든 원소를 순회하는 iteration에서, n + a번 호출되므로, 시간 복잡도는 O(n) |
| 16 | + - (a는 consecutive chunk의 개수이고 n보다 작거나 같음) |
| 17 | +
|
| 18 | +
|
| 19 | +Memory: 118.04 MB(Beats: 5.60 %) |
| 20 | +Space Complexity: O(n) |
| 21 | +- set, vis, cnt : O(n) |
| 22 | + */ |
| 23 | + |
| 24 | +class Solution { |
| 25 | + Set<Integer> set = new HashSet<>(); |
| 26 | + Map<Integer, Boolean> vis = new HashMap<>(); |
| 27 | + Map<Integer, Integer> cnt = new HashMap<>(); // key를 1번째 원소로 하는 연속한 증가 수열의 크기 |
| 28 | + |
| 29 | + public int longestConsecutive(int[] nums) { |
| 30 | + if (nums.length == 0) { |
| 31 | + return 0; |
| 32 | + } |
| 33 | + |
| 34 | + for (int num : nums) { |
| 35 | + if (set.contains(num)) { |
| 36 | + continue; |
| 37 | + } |
| 38 | + |
| 39 | + set.add(num); |
| 40 | + vis.put(num, false); |
| 41 | + cnt.put(num, 1); |
| 42 | + } |
| 43 | + |
| 44 | + int max = 0; |
| 45 | + for (int num : set) { |
| 46 | + int cnt = checkAbove(num); |
| 47 | + if (max < cnt) { |
| 48 | + max = cnt; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return max; |
| 53 | + } |
| 54 | + |
| 55 | + public Integer checkAbove(Integer num) { |
| 56 | + if (null == vis.get(num)) { |
| 57 | + return 0; |
| 58 | + } else if (vis.get(num)) { |
| 59 | + return cnt.get(num); |
| 60 | + } |
| 61 | + |
| 62 | + vis.put(num, true); |
| 63 | + int cntAbove = checkAbove(num + 1); |
| 64 | + if (cntAbove > 0) { |
| 65 | + cnt.put(num, cntAbove + 1); |
| 66 | + } |
| 67 | + |
| 68 | + return cntAbove + 1; |
| 69 | + } |
| 70 | +} |
0 commit comments