您的位置:首页 > 产品设计 > UI/UE

6: Longest Consecutive Sequence

2017-02-15 23:13 375 查看
注:本题的解法思想及参考的代码来自于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);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: