https://leetcode.com/problems/longest-consecutive-sequence/
정렬되지 않은 배열 주어지면 거기에서 제일 긴 연속된 숫자들의 길이 찾기, 단 시간 복잡도 안에.
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int max = 0;
for (int num : set) {
if (set.contains(num - 1)) {
continue;
}
int current = num;
int length = 1;
while (set.contains(current + 1)) {
current++;
length++;
}
max = Math.max(max, length);
}
return max;
}
핵심은 연속 수열 시작점에서만 탐색하는 것! (num - 1) 이 HashSet 안에 존재하는지를 확인해주면 된다.
정렬로 하는 풀이는 다음과 같다.
public int longestConsecutive(int[] nums) {
if (nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int count = 1;
int maxCount = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) { // 1 2 2 3 4 의 경우
continue;
}
if ((long) nums[i] - nums[i - 1] == 1) {
count++;
} else {
count = 1;
}
maxCount = Math.max(maxCount, count);
}
return maxCount;
}