LeetCode-----第128题-----最长连续序列

最长连续序列

难度:困难

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

题目分析:

   第一眼看到题目可能觉得会使用DP,因为是乱序的,所以用DP很难解。这里考虑使用set,将元素作为键存入set中,有两个作用:一个是去重;二个是方便查询。先将所有元素遍历一遍放入set中,在遍历,寻找每个序列的第一个元素,找到后在set中进行序列遍历并计数,找出最长序列。

参考代码:

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <deque>
#include <stack>
#include <algorithm>
#include <map>
#include <assert.h>
#include <memory>
#include<queue>
#include<functional>
#include <set>
#include <unordered_set>

using namespace std;

class Solution {
public:
	int longestConsecutive(vector<int>& nums) {
		if (nums.empty())
			return 0;

		unordered_set<int> nums_set;
		for (auto num : nums)//去重和方便查询
		{
			nums_set.insert(num);
		}

		int max_num = 0;
		for (auto num : nums_set)
		{
			if (!nums_set.count(num - 1))//找到每个连续序列的第一个值
			{
				int cur_num = num;
				int cur_count = 1;

				while (nums_set.count(cur_num + 1))//从第一个值向后计数
				{
					cur_num++;
					cur_count++;
				}
				max_num = max(max_num, cur_count);//记录最大的序列值
			}
		}
		return max_num;
	}
};

int main()
{
	Solution solution;
	vector<int> nums = { 100, 4, 200, 1, 3, 2 };
	cout << solution.longestConsecutive(nums) << endl;
	
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/L_smartworld/article/details/107699306