LeetCode Longest Consecutive Sequence

LeetCode解题之Longest Consecutive Sequence

原题

给定一组无序的整数,找出其中连续整数的最长长度。

注意点:

  • 算法时间复杂度为O(n)

例子:

输入: nums = [100, 4, 200, 1, 3, 2]

输出: 4 (连续整数为[1,2,3,4])

解题思路

采用了哈希法,所有的整数放入集合中,取出某一个元素向两边扩展,如果两边的元素也在集合中,从集合中去除这些元素的同时继续判断外围的元素,这样可以得到每一个连续整数组的长度。从这些长度中找到最长的长度。

AC源码

class Solution(object):
    def longestConsecutive(self, nums):
        """ :type nums: List[int] :rtype: int """
        numset, maxlen = set(nums), 0
        for n in set(nums):
            currlen, tmp = 1, n + 1
            while tmp in numset:
                currlen += 1
                numset.discard(tmp)
                tmp += 1
            tmp = n - 1
            while tmp in numset:
                currlen += 1
                numset.discard(tmp)
                tmp -= 1
            maxlen = max(maxlen, currlen)
        return maxlen


if __name__ == "__main__":
    assert Solution().longestConsecutive([100, 4, 200, 1, 3, 2]) == 4

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

你可能感兴趣的:(LeetCode,算法,python,set,hash)