Python with Set O(n)

  • 0

    Set is implemented with the hashing mechanism in Python. So the complexity is O(N)

    class Solution(object):
        def longestConsecutive(self, nums):
            :type nums: List[int]
            :rtype: int
            h = set()
            for n in nums:
            ans = 0
            while h:
                x = h.pop()
                count = 1
                a, b = x-1, x+1
                while a in h:
                    count += 1
                    a -= 1
                while b in h:
                    count += 1
                    b += 1
                ans = max(ans, count)
            return ans

Log in to reply

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