6: Longest Consecutive Sequence

来源:互联网 发布:手机淘宝如何找旗舰店 编辑:程序博客网 时间:2024/06/10 09:04

注:本题的解法思想及参考的代码来自于https://github.com/soulmachine/leetcode#leetcode题解

题目:
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.

解题思路:用一个哈希表unordered_map<int, bool> used 记录每个元素是否使用,对每个元素,以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度;

解法代码如下:

//寻找未排序数组的最长序列长度//时间复杂度O(n), 空间复杂度O(n)class Solution {public:        int longestConsecutive(const vector<int>& nums) {                unordered_map<int, bool> used;                for (const auto& i : nums) used[i] = false;                int longest = 0;                for (const auto& i : nums) {                        if (used[i]) continue;                        int length = 1;                        used[i] = true;                        for (int j = i + 1; used.find(j) != used.end(); ++j) {                                used[j] = true;                                ++length;                        }                        for (int j = i - 1; used.find(j) != used.end(); --j) {                                used[j] = true;                                ++length;                        }                        longest = max(longest, length);                }        }};
0 0
原创粉丝点击