0128. Longest Consecutive Sequence

https://leetcode.com/problems/longest-consecutive-sequence

Description

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:** nums = [100,4,200,1,3,2]
**Output:** 4
**Explanation:** The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

**Input:** nums = [0,3,7,2,5,8,4,6,0,1]
**Output:** 9

Constraints:

  • 0 <= nums.length <= 105

  • -109 <= nums[i] <= 109

ac1: priority queue

class Solution {
    public int longestConsecutive(int[] nums) {
        // edge cases
        if (nums.length < 2) return nums.length;

        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

        for (int i : nums) {
            pq.offer(i);
        }

        int max = 1;
        int len = 1;
        int prev = pq.poll();
        while (!pq.isEmpty()) {
            int n = pq.poll();
            if (n == prev + 1) {
                len++;
                max = Math.max(max, len);
            } else if (n > prev + 1) {
                len = 1;
            }
            prev = n;
        }

        return max;
    }
}
// priority queue

ac2: set

ac3: map

https://leetcode.com/problems/longest-consecutive-sequence/discuss/41055/My-really-simple-Java-O(n)-solution-Accepted

ac4: union find

https://leetcode.com/problems/longest-consecutive-sequence/discuss/41062/My-Java-Solution-using-UnionFound/39220

Last updated

Was this helpful?