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/
Sort of is O (Nlogn), really did not think of how O (n).
Looked at the set of Find, insert, delete is O (1).
OK, O (n) +o (n) or O (n).
In any case, the problem is not hard, the border is very clear, nothing but longestconsecutive ([]) and Longestconsecutive ([1]).
1 /**2 * @param {number[]} nums3 * @return {number}4 */5 varLongestconsecutive =function(nums) {6 varSet =NewSet ();7 for(vari = 0; i < nums.length; i++){8 if(!Set.has (Nums[i])) {9 Set.add (Nums[i]);Ten } One } A varMax = 0; - varCount = 0; - for(Iinchnums) { theCurr =Nums[i]; - if(Set.has (Nums[i])) { -Count = 1; -Set.Delete(Nums[i]); + } - while(Set.has (curr-1)){ + if(Set.has (curr-1)){ ACount + +; atSet.Delete(curr-1); -Curr-= 1; - } - } -Curr =Nums[i]; - while(Set.has (Curr + 1)){ in if(Set.has (Curr + 1)){ -Count + +; toSet.Delete(Curr + 1); +Curr + = 1; - } the } * $ if(Count >max) {Panax NotoginsengMax =count; - } the } + A returnMax; the};
[Leetcode] [JavaScript] Longest consecutive Sequence