美文网首页
128. Longest Consecutive Sequenc

128. Longest Consecutive Sequenc

作者: April63 | 来源:发表于2018-05-15 09:38 被阅读0次

这题的思路是先排序,这样连在一起的数字就可以相差1,但这样显然是不够的,因为没考虑到,相等的数字,所以count只在增加1的时候才增加,相等的时候不变,其他情况让count归1,代码如下:

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        if len(nums) == 1:
            return 1
        n = len(nums)
        nums.sort()
        count = 1
        max_count = 1
        for i in range(1, len(nums)):
            if nums[i] == nums[i-1] + 1:
                count += 1
            elif nums[i] == nums[i-1]:
                count = count
            else:
                count = 1
            max_count = max(count, max_count)
        return max_count

因为有对时间复杂度的要求,对于排序本身来说最少需要nlogn,所以,需要考虑一种新的做法,新做法是以空间换取时间,代码如下,用字典记录,建立字典过程是o(n)
class Solution:
# @param num, a list of integer
# @return an integer
def longestConsecutive(self, num):
dict = {x: False for x in num} # False means not visited
maxLen = 0
for i in dict:
if dict[i] == False:
curr = i+1; lenright = 0
while curr in dict:
lenright += 1; dict[curr] = True; curr += 1
curr = i-1; lenleft = 0
while curr in dict:
lenleft += 1; dict[curr] = True; curr -= 1
maxLen = max(maxLen, lenleft+1+lenright)
return maxLen

相关文章

网友评论

      本文标题:128. Longest Consecutive Sequenc

      本文链接:https://www.haomeiwen.com/subject/bzcsdftx.html