✉️문제
https://leetcode.com/problems/longest-consecutive-sequence/description/
Longest Consecutive Sequence - LeetCode
Can you solve this real interview question? Longest Consecutive Sequence - Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input:
leetcode.com
🗝 문제풀이
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int n : nums) set.add(n);
int answer = 0;
for(int n : set) {
int length = 1;
if(!set.contains(n - 1)) {
while(set.contains(n + length)) {
length++;
}
answer = Math.max(answer, length);
}
}
return answer;
}
}