首页 > 其他 > 详细

128. 最长连续序列

时间:2020-02-18 13:36:21      阅读:48      评论:0      收藏:0      [点我收藏+]

 

Q:

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)。

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

A:

注意一点,题目说的序列长度是有几个连续+1的数。
然后题目不让用排序,用dict或者set做,这样就是O(N)复杂度,一个比较巧妙的地方:用当前元素减1的值试探集合,存在的话当前元素肯定不是其中一段最长连续子序列的起点,故跳过。

c++:

 1 class Solution {
 2 public:
 3     int longestConsecutive(vector<int>& nums) {
 4         unordered_set<int> st;
 5         for(int &num:nums){
 6             st.insert(num);
 7         }
 8         int res=0;
 9         for(int t:st){
10             if(st.count(t-1)){
11                 continue;
12             }
13             int cnt=0;
14             while(st.count(t)){
15                 ++t;
16                 ++cnt;
17             }
18             res=max(res,cnt);
19         }
20         return res;
21     }
22 };

python:

 1 class Solution:
 2     def longestConsecutive(self, nums: List[int]) -> int:
 3         nums=set(nums)
 4         res=1 if nums else 0
 5         for x in nums:
 6             if x-1 not in nums:
 7                 cur,y=1,x
 8                 while y+1 in nums:
 9                     cur+=1
10                     y+=1
11                 res=max(res,cur)
12         return res
13         

 


128. 最长连续序列

原文:https://www.cnblogs.com/FdWzy/p/12288151.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!