128. Longest Consecutive Sequence

来源:互联网 发布:java开发电脑配置要求 编辑:程序博客网 时间:2024/06/07 05:08

Problem:

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。而且要求程序复杂度大致在O(n)范围。如果用暴力算法,复杂度是O(n^2),好一点的就先排序再求,那复杂度是O(nlogn),所以都达不到要求。而要在O(n)里完成,那我觉得用哈希应该是一个方式,但是怎么去用哈希呢?然后我在stl中找到了用了哈希实现的unordered_map类,里面实现了<键值,元素>的匹配。所以首先是决定使用<int,bool>,其中int是数组中的元素,bool是是否已经使用过了。然后初始化unorder_map。对于每个元素,向前后进行find,假如存在,长度++,并且bool设为true表示使用过了。否则结束内存循环。代码如下:


Code:(LeetCode运行9ms):

class Solution {public:    int longestConsecutive(vector<int>& nums) {        unordered_map<int, bool> map;        int longest = 0;        //初始化map        for (auto i : nums) {            map[i] = false;        }                for (auto i : nums) {            if (map[i]) {                continue;            }            int length = 1;            map[i] = true;            //向前后搜索,其中find()失败会返回end()的迭代器,所以判断可以用!=            for (int j = i + 1; map.find(j) != map.end(); j++) {                length++;                map[j] = true;            }                        for (int j = i - 1; map.find(j) != map.end(); j--) {                length++;                map[j] = true;            }            longest = max(longest, length);        }        return longest;    }};


如果想要知道更多unorder_map的知识,以下是内部函数和实现的网页:

https://msdn.microsoft.com/zh-cn/library/bb982522.aspx#unordered_map__equal_range

原创粉丝点击