128. Longest consecutive sequence

https://leetcode.com/problems/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: 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.


  • code
class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> s = Set.copyOf(Arrays.stream(nums).boxed().collect(Collectors.toList()));
        // Set<Integer> s = new HashSet<>(Arrays.stream(nums).boxed().collect(Collectors.toList()));

        // Set<Integer> s = new HashSet<Integer>();
        // for (int num : nums)  s.add(num);

        int longest = 0;
        for (int v: s){
            if (s.contains(v + 1)) continue;
            int curLong = 0;
            while(s.contains(v--)) curLong++;
            longest = Math.max(longest, curLong);
        }
        return longest;
    }
}
  • code
class Solution {
    public int longestConsecutive(int[] nums) {
        HashSet<Integer> s = new HashSet<>(Arrays.stream(nums).boxed().collect(Collectors.toList()));
        int longest = 0;
        for (int v: nums){
            if (!s.contains(v - 1)){
                int cur = 0;
                while (s.contains(v)){
                    v++;
                    cur++;
                }
                longest = Math.max(longest, cur);    
            }
        }
        return longest;
    }
}
  • code
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        res, nums_set = 0, set(nums)

        for num in nums:
            if num - 1 in nums_set: continue
            cur_longest = 1
            while num + cur_longest in nums_set:
                cur_longest += 1
            res = max(res, cur_longest)
        return res