Remove number from set consecutively, a dry python code

  • 9
    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:
                m -= 1
                length += 1
            while n+1 in numbers:
                n += 1
                length += 1
            max_len = max(max_len, length)
        return max_len

    keep trace of the max_len

  • 1

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

  • 0

    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.