leetcode【128】Longest Consecutive Sequence【c++,beats80%】

问题描述:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

源码:

感觉最近进了“红区”,题目难度都不小。这题我看了第一眼就想用map,但是搞半天,怎么搞都有重复的部分。后来在Discuss区看到了一个大佬用的,每次执行的是st[item-left]而不是st[item-1],解决了问题。时间79%,空间100%。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int n = nums.size(), result = 0;
        if(n==0)    return result;
        unordered_map<int, int> st;
        for(auto item: nums){
            if(st.count(item))     continue;
            int left=0, right=0;
            if(st.count(item-1))    left = st[item-1];
            if(st.count(item+1))    right = st[item+1];
            if(left>0 && right==0){
                st[item] = 1+left;
                st[item-left] = 1+left;
            }
            else if(left==0 && right>0){
                st[item] = 1+right;
                st[item+right] = 1+right;                
            }
            else if(left>0 && right>0){
                st[item] = 1+left+right;
                st[item-left] = 1+left+right;;
                st[item+right] = 1+left+right;;
            }
            else{
                st[item] = 1;
            }
            result = max(result, st[item]);
        }
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值