Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9
Constraints:
0 <= nums.length <= 104
-109 <= nums[i] <= 109
题目链接:https://leetcode.com/problems/longest-consecutive-sequence/
思路:先给数组排序,然后利用一个额外的dp数组计算最大连续个数。初始化dp的时候全是1。注意遇到 A A,这种情况,dp[i]=dp[i-1],然后continue就可以了。
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int len=nums.size();
if(len<=1)
{
return len;
}
sort(nums.begin(),nums.end());
vector<int> dp(len+1,1);
int ans=1;
for(int i=1;i<len;i++)
{
if(nums[i]==nums[i-1])
{
dp[i]=dp[i-1];
continue;//[1,2,0,1],排序后[0,1,1,2]这种情况输出3
}
if(nums[i]==(nums[i-1]+1))
{
dp[i]=dp[i-1]+1;
}
ans=max(dp[i],ans);
}
return ans;
}
};