【LeetCode】6.Longest Consecutive Sequence

题目描述(Hard)

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.Your algorithm should run in O(n) complexity.

题目链接

https://leetcode.com/problems/median-of-two-sorted-arrays/description/

Example 1:

 Input: [100, 4, 200, 1, 3, 2]
 Output: 4
 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

算法分析

hash表来解决这个问题

法一:先初始化一个hash表, 存储所有数组元素, 然后遍历这个数组, 对找到的数组元素, 去搜索其相连的上下两个元素是否在hash表中,以该元素为中心往左右扩张,直到不连续位置,记下最长的长度。

法二:先初始化一个hash表, 存储所有数组元素作为边界时最长长度;假设遍历到元素cur,记录以cur及前后元素为边界的最大长度。

提交代码(法一):

class Solution {
public:
	int longestConsecutive(vector<int>& nums) {
		unordered_map<int, bool> map;

		for (int &each : nums) map[each] = false;

		int longest = 0;

		for (int &each : nums)
		{
			if (map[each]) continue;

			int length = 1;
			map[each] = true;

			for (int i = each + 1; map.find(i) != map.end(); ++i)
			{
				map[i] = true;
				++length;
			}

			for (int i = each - 1; map.find(i) != map.end(); --i)
			{
				map[i] = true;
				++length;
			}

			longest = max(longest, length);
		}

		return longest;
	}
};

提交代码(法二):

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

		unordered_map<int, int> map;
		int longest = 1;

		for (int &each : nums)
		{
			if (map.find(each) != map.end()) continue;

			map[each] = 1;

			if (map.find(each - 1) != map.end())
				longest = max(longest, mergeCluster(map, each - 1, each));

			if (map.find(each + 1) != map.end())
				longest = max(longest, mergeCluster(map, each, each + 1));
		}

		return longest;
	}

	int mergeCluster(unordered_map<int, int> &map,
		int left, int right)
	{
		// 找到上下边界
		int lower = left - map[left] + 1;
		int upper = right + map[right] - 1;
		int length = upper - lower + 1;
		map[lower] = length;
		map[upper] = length;

		return length;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int>& nums, int expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	int result = s.longestConsecutive(nums);

	if (result == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{

	vector<int> array1 = { 100, 4, 200, 1, 3, 2 };
	vector<int> array2 = { 1, 20, 19, 18, 3, 4, 5 };
	vector<int> array3 = { 2 };

	Test("Test1", array1, 4);
	Test("Test2", array2, 3);
	Test("Test3", array3, 1);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/81911313