LeetCode:2.1.6 Longest Consecutive Sequence

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> umap存儲num中的所有數據,並初始化爲false。然後順序讀取num,每讀到一個數,就在umap的左右兩邊順序遍歷,查找相鄰的連續元素是否出現,若找到,就將其值爲true,防止下次重複訪問

代碼:

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int LongestConsecutive(vector<int>& num)
{
	unordered_map<int,bool> umap;

	for (int i=0;i<num.size();i++)
	{
		umap[num[i]] = false;
	}
	

	int longest=1;

	for (int i=0;i<num.size();i++)
	{
		
		if (umap[num[i]])
			continue;

		umap[num[i]] = true;

		int temp=1;

		for (int j=num[i]-1;umap.find(j)!=umap.end();j--)
		{
			umap[j] = true;
			temp++;
		}

		for (int j=num[i]+1;umap.find(j)!=umap.end();j++)
		{
			umap[j] = true;
			temp++;
		}

		

		if (temp>longest)
		{
			longest = temp;
		}

	}

	return longest;

}


int main()
{
	int num[]={4,3,6,8,7,9,10,1,12,18,27,26,25,24,23};

	int length = sizeof(num)/sizeof(int);

	vector<int> vec(num,num+length);

	int longest = LongestConsecutive(vec);

	cout<<longest<<endl;

	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章