You get an array nums of integers, in no particular order.
Return the length of the longest run of consecutive values.
Consecutive values go up by 1 each time. For example, 5, 6 and 7 form a run of length 3.
The values of a run can be anywhere in nums. A value that appears more than once counts only once.
Example 1:
Input: nums = [9, 13, 10, 5, 11, 6] Output: 3 Explanation: 9, 10 and 11 make the longest run. 5 and 6 make a shorter run. 13 stands alone.
Example 2:
Input: nums = [-2, 0, -1, 0, 2, -1] Output: 3 Explanation: The longest run is -2, -1 and 0. 0 and -1 appear twice, but each counts once. 2 is not in the run, because 1 is missing.
Example 3:
Input: nums = [40, 10, 30, 20] Output: 1 Explanation: No two values are 1 apart. So every run has just one value.
Constraints:
numshas 1 to 30,000 integers.- Each value is from -100 to 100,000,000.
Note:
Your algorithm should run in O(n) time and use O(n) extra space.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Solution #2 · O(n)
Free plan: 30 tutor messages. PRO is unlimited.
