|
| 1 | +// 중복여부만 제거하고 포함여부로 판단 O(N) |
| 2 | +class Solution { |
| 3 | + public int longestConsecutive(int[] nums) { |
| 4 | + if (nums == null || nums.length == 0) { |
| 5 | + return 0; |
| 6 | + } |
| 7 | + |
| 8 | + HashSet<Integer> set = new HashSet<>(); |
| 9 | + for (int num : nums) { |
| 10 | + set.add(num); |
| 11 | + } |
| 12 | + |
| 13 | + int maxLength = 0; |
| 14 | + |
| 15 | + for (int num : set) { |
| 16 | + if (!set.contains(num - 1)) { |
| 17 | + int currentNum = num; |
| 18 | + int count = 1; |
| 19 | + while (set.contains(currentNum + 1)) { |
| 20 | + currentNum++; |
| 21 | + count++; |
| 22 | + } |
| 23 | + |
| 24 | + maxLength = Math.max(maxLength, count); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + return maxLength; |
| 29 | + } |
| 30 | +} |
| 31 | +// 정렬이 들어가면 O(nlogn) 아래로 줄일 수 없음 |
| 32 | +class Solution { |
| 33 | + public int longestConsecutive(int[] nums) { |
| 34 | + if(nums.length == 0) return 0; |
| 35 | + TreeSet<Integer> set = new TreeSet<>(); |
| 36 | + for (int num : nums) { |
| 37 | + set.add(num); |
| 38 | + } |
| 39 | + int max = 1; |
| 40 | + int consecutiveCount = 1; |
| 41 | + int prev = set.pollFirst(); |
| 42 | + while(!set.isEmpty()) { |
| 43 | + int next = set.pollFirst(); |
| 44 | + if (next - prev == 1) { |
| 45 | + consecutiveCount++; |
| 46 | + } else { |
| 47 | + max = Math.max(consecutiveCount, max); |
| 48 | + consecutiveCount = 1; |
| 49 | + } |
| 50 | + prev = next; |
| 51 | + } |
| 52 | + return Math.max(max, consecutiveCount); |
| 53 | + } |
| 54 | +} |
| 55 | +// 이중 변환 필요 없음 |
| 56 | +class Solution { |
| 57 | + public int longestConsecutive(int[] nums) { |
| 58 | + if(nums.length == 0) return 0; |
| 59 | + HashSet<Integer> set = new HashSet<>(); |
| 60 | + for (int num : nums) { |
| 61 | + set.add(num); |
| 62 | + } |
| 63 | + PriorityQueue<Integer> pq = new PriorityQueue<>(set); |
| 64 | + int max = 1; |
| 65 | + int consecutiveCount = 1; |
| 66 | + int prev = pq.poll(); |
| 67 | + while(!pq.isEmpty()) { |
| 68 | + int next = pq.poll(); |
| 69 | + if (next - prev == 1) { |
| 70 | + consecutiveCount++; |
| 71 | + } else { |
| 72 | + max = Math.max(consecutiveCount, max); |
| 73 | + consecutiveCount = 1; |
| 74 | + } |
| 75 | + prev = next; |
| 76 | + } |
| 77 | + return Math.max(max, consecutiveCount); |
| 78 | + } |
| 79 | +} |
0 commit comments