Remove number from set consecutively, a dry python code


  • 9
    T
    class Solution:
    # @param num, a list of integer
    # @return an integer
    def longestConsecutive(self, num):
        numbers = set(num)
        max_len = 0
        while numbers:
            m = n = numbers.pop()
            length = 1
            while m-1 in numbers:
                numbers.remove(m-1)
                m -= 1
                length += 1
            while n+1 in numbers:
                numbers.remove(n+1)
                n += 1
                length += 1
            max_len = max(max_len, length)
        return max_len
    

    keep trace of the max_len


  • 0
    P

    it seems that your time is O(n^2) since each poped elements are checked in the list for its adj. elements.


  • 0
    H

    Not exactly. set() is a hashtable


Log in to reply
 

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