The longest continuous sequence (C++ solution)

topic

Given an unsorted array of integers  nums , find the length of the longest sequence of consecutive numbers (the sequence elements are not required to be consecutive in the original array).

Please design and implement  O(n) an algorithm with time complexity to solve this problem.

Example 1:

Input: nums = [100,4,200,1,3,2]
 Output: 4
 Explanation: The longest continuous sequence of numbers is [1, 2, 3, 4]. Its length is 4.

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
 Output: 9

C++ code

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

/*
* 最长连续序列问题
* 定义一个无序set容器,放入数组元素
* 定义初始数字和连续序列个数,如果容器中有下一个连续数字,加1继续循环
* 最终得出最长连续序列个数
*/
int longestConsecutive(vector<int>& nums) {
	unordered_set<int> num_set;
	for (const int& num : nums) {
		num_set.insert(num);
	}

	int longestStreak = 0;
	for (const int& num : num_set) {
		if (!num_set.count(num - 1)) {
			int currentNum = num;
			int currentStreak = 1;
			while (num_set.count(currentNum + 1)) {
				currentNum += 1;
				currentStreak += 1;
			}
			longestStreak = max(longestStreak, currentStreak);
		}
	}
	return longestStreak;
}

int main() {
	vector<int> nums = { 100,4,200,1,3,2 };
	int longestStreak = longestConsecutive(nums);
	cout << longestStreak << endl;
	return 0;
}

analyze

For the longest continuous sequence problem, define an unordered set container, put in the array elements, define the initial number and the number of consecutive sequences, if there is the next consecutive number in the container, add 1 and continue the loop, and finally get the number of the longest continuous sequence. .

Guess you like

Origin blog.csdn.net/m0_62275194/article/details/133970662