128. Longest Consecutive Sequence最长连续序列

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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值