Longest Consecutive Sequence(最长数组值连续序列)

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.
/* 找出数组中连续序列的最大长度(位置可以不连续)
 * 本质上是进行查找: 找到这个元素相邻的。。
 * 1.进行去重, 不能用set, 用unordere_set 前者是基于比较的 复杂度为O(nlogn)
 * 2.设立mask
 * 2.每次从当前数字x开始遍历, 利用set中元素查找x-1 x+1 找到就应该在num中删除相应元素表示构成一个连续序列
 *  但是大量删除操作会增加复杂度 用mask代表已经被使用?
 * */
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if(nums.size()<2)   return nums.size();// 0 或者 1
        int len=nums.size(), maxlen=0;//
        // 设立unordermap
        unordered_map<int, bool> m;
        for(int &num : nums){
            m.insert(pair<int, bool>(num, false));
        }
        for(auto it : m){
            if(it.second)   continue;
            int left=it.first-1, right=it.first+1;
            while(m.count(left)){
                m[left]=true;
                left--;
            }
            while(m.count(right)){
                m[right]=true;
                right++;
            }
            maxlen = max(maxlen, right-left-1);
        }
        return maxlen;
    }
};

猜你喜欢

转载自blog.csdn.net/futangxiang4793/article/details/88912413