LeetCode

来源:互联网 发布:雍正 知乎 编辑:程序博客网 时间:2024/06/05 06:03

原题网址:
https://leetcode.com/problems/longest-consecutive-sequence/#/description

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

题解:
先对序列进行增序排序,然后依次遍历,用一个变量统计最大次数就可以了。

代码:

class Solution(object):    def longestConsecutive(self, nums):        """        :type nums: List[int]        :rtype: int        """        if len(nums)==0: return 0        nums = sorted(nums)        print(nums)        count = 1        maxcount = 1        for i in range(1,len(nums)):            if nums[i]-nums[i-1]==1:                count += 1                print(count)            if nums[i]-nums[i-1]>1:                if maxcount < count:                    maxcount = count                count=1        if maxcount < count:            maxcount = count        return maxcount