[LeetCode] 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.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Example 3:
Input: nums = [1,0,1,2]
Output: 3
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
最长连续序列。
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-consecutive-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
思路是在遍历数组的时候,第一次遍历先用 hashset 存住所有的元素。再遍历第二次,第二次遍历的时候,找每一个元素的 left (num - 1) 和 right (num + 1),若找到,就在 hashset 中移除,同时移动 left 和 right 的位置。最终最长的子序列长度为 right - left - 1。
复杂度
时间O(n)
空间O(n)
代码
Java实现
1 |
|
JavaScript实现
1 |
|