每天两道LeetCodeHard:(21)

148 阅读1分钟

128. Longest Consecutive Sequence

第一个考察连续性的题

题干:

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

Your algorithm should run in O(n) complexity.

解释:

首先给了我们一个无序数组,让我们返回最长的连续序列,而且要求是一次遍历实现。

思考:

因为是序列,所以其实就是对每一个元素,判断它是否有以它为终点的其他元素,也就是寻找比它小一个的元素;如果找到了就把当前元素添加到对应列表的末尾,并且更新最大长度即可。时间效率44%

答案:

from collections import defaultdict
class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        countSet=defaultdict(int)
        length=0
        for i in nums:
            countSet[i]=0
        
        for i in nums:
            if countSet[i]==1:
                continue
            else:
                left=self.findLeft(countSet,i)
                right = self.findRight(countSet,i)
                length=max(length,left+right+1)
        return length
    
    def findLeft(self,countSet,i):
        if i-1 in countSet:
            countSet[i-1]=1
            return self.findLeft(countSet,i-1)+1
        else:
            return 0
    def findRight(self,countSet,i):
        if i+1 in countSet:
            countSet[i+1]=1
            return self.findRight(countSet,i+1)+1
        return 0

答案补充:

看了很多题解,就是这个思路没错,遍历两次,不知道为什么只赢了44%