LeetCode - 128. Longest Consecutive Sequence - 思路详解- C++

来源:互联网 发布:澳门网络真人博客官网 编辑:程序博客网 时间:2024/06/08 14:00

题目

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

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

翻译

假设有一个未排序整数数组,找出数组中最长的连续序列。

比如:数组【100,4,200,1,3,2】
最长的连续序列为【1,2,3,4】。则返回其长度为4

思路

我们使用map来求解。
首先将所有的数字映射到map<\int,bool>即表示该数存在
然后遍历数组,对每一个数组num[i],
每次加一,只要其存在且连续,同时计数加1。同时删除map中该元素。
每次减一,只要其存在且联系,同时计数加1。然后删除map中元素。
然后比较更新max。
分析:
将所有元素映射到map中时间复杂度为O(nlog);
然后判断是存在,时间复杂度为O(n)
删除元素,时间复杂度为O(nlogn)
所以整体时间时间复杂读为O(nlogn)

代码

class Solution {public:    int longestConsecutive(vector<int>& nums) {        map<int,bool> nums_map;        for(int i = 0; i < nums.size(); i++){            nums_map[nums[i]] = true;        }        int max = 0;        for(int i = 0; i < nums.size(); i++){            if(nums_map.count(nums[i]) != 0){                int down = nums[i]-1;                int up = nums[i]+1;                int cnt = 1;                nums_map.erase(nums[i]);    //清除                while(nums_map.count(down) != 0){                    //cout << "down " << down << endl;                    cnt++;                    nums_map.erase(down);                    down--;                }                while(nums_map.count(up) != 0){                    //cout << "up " << up << endl;                    cnt++;                    nums_map.erase(up);                    up++;                }                //cout << cnt << endl;                if(cnt > max){                    max = cnt;                }            }        }        return max;    }};
0 0
原创粉丝点击