一、原题目
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
二、题目大意
给定一个含有数字的列表,求连续数的最大长度。
三、思路分析
别人的思路:
利用集合去掉nums中重复元素,弹出一个数n,从n开始向后开始依次加一得到一个中间数n1,如果n1在nums中列表长度cout加一,并删除n1,否则从n开始向前依次减一得到一个n2,如果n2在nums中cout加一,并删除n2,否则统计最大长度。只要nums中还有元素,重复以上过程,否则返回最大长度。
本人的思路:
对列表进行排序,如果nums[i-1]+1==nums[i],计数器cout加一,当不相等时,cout的值存储到列表n中,cout=1
返回n的最大值。(由于这里讨论情况很多,详情见代码)
四、具体代码
作者的代码:
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
longest_consecutive = 0
# put all numbers into a set
distinct_numbers = set(nums)
while distinct_numbers:
# each number itself has a consecutive count of 1
consecutive = 1
# we will pop any number
number = distinct_numbers.pop()
# let's find all consecutive numbers higher than "number"
next_number = number + 1
while next_number in distinct_numbers:
distinct_numbers.remove(next_number)
next_number += 1
consecutive += 1
# let's find all consecutive numbers lower than "number"
next_number = number - 1
while next_number in distinct_numbers:
distinct_numbers.remove(next_number)
next_number -= 1
consecutive += 1
# update longest_consecutive accordingly
longest_consecutive = max(longest_consecutive, consecutive)
return longest_consecutive
本人的代码:
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums.sort()
if len(nums)==0:#列表长度为0
return 0
elif len(nums)==1:#列表长度为1
return 1
elif len(nums)==2:#列表长度为2
if nums[0]==nums[1]-1:#两个元素相等
return 2
else:
return 1#两个元素不相等
else:
n=[]
cout=1#计数器,初始值为1
for i in range(1,len(nums)):
if nums[i-1]==nums[i]-1:#两个数连续
cout+=1
n.append(cout)#会产生一些中间结果,但是没有关系,我们只要最大值
elif nums[i-1]==nums[i]:#两个数相等,跳过
pass
else:
n.append(cout)#不相等,这个“子整数连续列”结束,开始下一个连续列。cout置1
cout=1
return max(n)
五、两者差别
这道题目的讨论比较多,本人之所以写出来也是因为测试数据很特殊,看到了思维的漏洞。如果您有兴趣把那些情况去掉,测试代码,看看会是怎么样的结果,收获会很多。本人的思路直接处理,直接讨论,思路还算简单,但是显得不够灵活。
作者的思维就比较全面了,这个因为作者考虑问题的角度是:弹出的数是一个“中间数”,它的前面和后面都会构成连续的整数序列,但是本人的思考角度是:弹出的数是一个“最小数”,只能通过加一操作来实现连续的整数序列。
这也可能是本人代码为什么那么多讨论的原因了。
作者的代码看起来有三个循环,而本人只有一个循环,但是代码的运行的时间作者的比本人的快四秒。
本人的时间消耗可能是花在了排序的事情上。
六、知识点总结
1.集合中元素不重复特点的使用,pop从集合中获取元素的方法
2.对于一个连续整数序列,给定一个数,那么这个数前面和后面都有可能构成序列。
七、.来源
题目连接:https://leetcode.com/problems/longest-consecutive-sequence/
座右铭:站在别人的思想上,看见自己的不足,传播错误的经验,愿君不重蹈覆辙。
由于受限于本人经验,难免不足,如有建议,欢迎留言交流。
说明:作者代码和本人代码都能通过测试,本人亲测。如果喜欢,请点赞,您的鼓励是本人前进的最好动力。
---------------------
作者:路漫漫,远修兮
来源:CSDN
原文:https://blog.csdn.net/qq_41827968/article/details/88756403
版权声明:本文为博主原创文章,转载请附上博文链接!