[LeetCode/Medium] 128. Longest Consecutive Sequence (JAVA)

Jiwoo Kim·2021년 6월 7일
0

알고리즘 정복하기

목록 보기
83/85
post-thumbnail

문제


Set 풀이

코드

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) set.add(num);
        
        int max = 0;
        for (int num : set) {
            int length = 1;
            
            if (!set.contains(num-1)) {
                int target = num+1;
                while (set.contains(target++)) 
                    length++;
            }
            
            max = Math.max(max, length);
        }
        return max;
    }
}

DP 풀이


Union Find 풀이

0개의 댓글