【算法刷题】leetcode 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.

 

由于排序的复杂度是nlogn,因此不能先排序,考虑空间换时间

第一次遍历数组,用一个map存储make_pair(数组值,1)

第二次遍历数组,对于每一个数值value,可以连续遍历value+1,value+2·······看是否再map中,若在,则len+1,且把map中对应的值修改为-1,递增遍历完后,再遍历value-1,value-2·······,相同的方式

以此遍历数组中的每一个数,对于后续中map中对应值为-1的可以不用再计算,之前肯定都算过,可以跳过

 

最后maxlen为第二次遍历每个数时的最大len

   int longestConsecutive(vector &num) {
		if (num.empty())
			return 0;
		map number;
		for (auto a : num)
			number.insert(make_pair(a, 1));

		int len(1),maxlen(1);
		for (auto b : num)
		{
			if (number[b]>0)
			{
				len = 1;
				int value = b + 1;
				for (; number.find(value) != number.end(); ++value)
				{
					number[value] = -1;
					++len;
				}
				value = b - 1;
				for (; number.find(value) != number.end(); --value)
				{
					number[value] = -1;
					++len;
				}
				maxlen = max(maxlen, len);
			}

		}

		return maxlen;
    }

 

你可能感兴趣的:(算法题)