Very simple and easy to understand solution


  • 0
    D
    # @param {Integer[]} nums
    # @return {Integer}
    def longest_consecutive(nums)
        return 0 if nums.nil? || nums.empty?
        max = 0
        range = {}
        visited = {}
        nums.each do |num|
            next if visited[num]
            visited[num] = true
            h = t = num
            h1, t1 = range[num-1]
            h2, t2 = range[num+1]
            h = h1 if h1
            t = t2 if t2
            range[num] = range[h] = range[t] = [h, t]
            max = [max, t - h + 1].max
        end
        max
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.