Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Your algorithm should run in O(n) complexity.
https://leetcode.com/problems/longest-consecutive-sequence/
排序一下就是O(nlogn)了,真心没想出如何O(n)。
看了一下说set的查找,插入,删除都是O(1)。
好吧,O(n)+O(n)还是O(n)。
无论如何,这题不算hard吧,边界情况也很明确,无非就是longestConsecutive([])和longestConsecutive([1])。
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var longestConsecutive = function(nums) { 6 var set = new Set(); 7 for(var i = 0; i < nums.length; i++){ 8 if(!set.has(nums[i])){ 9 set.add(nums[i]); 10 } 11 } 12 var max = 0; 13 var count = 0; 14 for(i in nums){ 15 curr = nums[i]; 16 if(set.has(nums[i])){ 17 count = 1; 18 set.delete(nums[i]); 19 } 20 while(set.has(curr - 1)){ 21 if(set.has(curr - 1)){ 22 count ++; 23 set.delete(curr - 1); 24 curr -= 1; 25 } 26 } 27 curr = nums[i]; 28 while(set.has(curr + 1)){ 29 if(set.has(curr + 1)){ 30 count ++; 31 set.delete(curr + 1); 32 curr += 1; 33 } 34 } 35 36 if(count > max){ 37 max = count; 38 } 39 } 40 41 return max; 42 };
时间: 2024-10-25 12:44:42