128. Longest Consecutive Sequence

题目大意

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

中文释义

给定一个未排序的整数数组 nums,返回最长连续元素序列的长度。

你必须编写一个在 O(n) 时间内运行的算法。

示例

Example 1:

Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: 最长连续元素序列是 [1, 2, 3, 4]。因此它的长度是 4。

Example 2:

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

限制条件

0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9

解题思路

方法

即在一个未排序的整数数组中找出最长的连续元素序列的长度。为了达到 O(n) 的时间复杂度,使用了哈希集合(unordered_set)来存储数组中的所有元素,这使得查找特定元素的操作变得非常快速。

创建哈希集合:

使用 unordered_set 将数组 nums 中的所有元素添加到集合中。这样可以在 O(1) 时间复杂度内判断一个元素是否存在于集合中。 遍历数组:

遍历数组 nums 中的每个元素 num:

首先检查 num - 1 是否存在于集合中,以确定 num 是否是一个连续序列的起始点。如果 num 是起始点,则从 num 开始向后查找连续的数字,直到找不到下一个连续的数字。 查找并更新最长序列:

对于每个起始点,计算从该点开始的连续序列的长度,并更新最长序列的长度。 返回结果:

最终返回计算得到的最长连续序列的长度。

代码

class Solution {

public:

int longestConsecutive(vector& nums) {

unordered_set num_set(nums.begin(), nums.end());

int longestStreak = 0;

for (int num : nums) {

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;

}

};

精彩内容

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: