sajaniemi_variable_dataset_large / code /train /JavaScript /0004792_leetcode128_LongestConsecutiveSequence.js
Download code/train/JavaScript/0004792_leetcode128_LongestConsecutiveSequence.js from Variable-role/sajaniemi_variable_dataset_large: direct link, hf CLI and curl.
- Browser
- Download file 1.31 kB
-
https://huggingface.co/datasets/Variable-role/sajaniemi_variable_dataset_large/resolve/main/code/train/JavaScript/0004792_leetcode128_LongestConsecutiveSequence.js
- Command line
-
hf download hf://datasets/Variable-role/sajaniemi_variable_dataset_large/code/train/JavaScript/0004792_leetcode128_LongestConsecutiveSequence.js
-
curl -L -o 0004792_leetcode128_LongestConsecutiveSequence.js https://huggingface.co/datasets/Variable-role/sajaniemi_variable_dataset_large/resolve/main/code/train/JavaScript/0004792_leetcode128_LongestConsecutiveSequence.js
1.31 kB
| // Given an unsorted array of integers, find the length of the longest consecutive elements sequence. | |
| // Your algorithm should run in O(n) complexity. | |
| // Example: | |
| // Input: [100, 4, 200, 1, 3, 2] | |
| // Output: 4 | |
| // Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. | |
| /** | |
| * @param {number[]} nums | |
| * @return {number} | |
| * score:30.77(80ms) | |
| * time:O(nlogn) | |
| * space:O(n) | |
| */ | |
| var longestConsecutive = function (nums) { | |
| nums = Array.from(new Set(nums)); | |
| if (nums.length < 1) { | |
| return 0; | |
| } | |
| nums.sort((a, b) => a - b); | |
| let max = 1; | |
| let cur = 1; | |
| for (let i = 1; i < nums.length; i++) { | |
| if (nums[i] - nums[i - 1] === 1) { | |
| cur++; | |
| } else { | |
| if (cur > max) { | |
| max = cur; | |
| } | |
| cur = 1; | |
| } | |
| } | |
| return Math.max(cur, max); | |
| }; | |
| /** | |
| * @param {number[]} nums | |
| * @return {number} | |
| * score:94.51(54ms) | |
| * time:O(n) | |
| * space:O(n) | |
| */ | |
| var longestConsecutive2 = function (nums) { | |
| let best = 0; | |
| let s = new Set(nums); | |
| for (let i of s) { | |
| if (!s.has(i - 1)) { | |
| let cur = i + 1; | |
| while (s.has(cur)) { | |
| cur++; | |
| } | |
| best = Math.max(best, cur - i); | |
| } | |
| } | |
| return best; | |
| }; |