[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
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 class Solution { 2 public int longestConsecutive(int[] nums) { 3 // corner case 4 if (nums == null || nums.length == 0) { 5 return 0; 6 } 7 8 // normal case 9 int res = 0; 10 HashSet<Integer> set = new HashSet<>(); 11 for (int num : nums) { 12 set.add(num); 13 } 14 for (int i = 0; i < nums.length; i++) { 15 int down = nums[i] - 1; 16 while (set.contains(down)) { 17 set.remove(down); 18 down--; 19 } 20 int up = nums[i] + 1; 21 while (set.contains(up)) { 22 set.remove(up); 23 up++; 24 } 25 res = Math.max(res, up - down - 1); 26 } 27 return res; 28 } 29 }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var longestConsecutive = function(nums) { 6 let res = 0; 7 let set = new Set(); 8 for (let i = 0; i < nums.length; i++) { 9 let num = nums[i]; 10 set.add(num); 11 } 12 for (let i = 0; i < nums.length; i++) { 13 let cur = nums[i]; 14 let down = cur - 1; 15 while (set.has(down)) { 16 set.delete(down); 17 down--; 18 } 19 let up = cur + 1; 20 while (set.has(up)) { 21 set.delete(up); 22 up++; 23 } 24 res = Math.max(res, up - down - 1); 25 } 26 return res; 27 };