Given nums, an integer array, find the length of the longest consecutive sequence of distinct values. A consecutive sequence contains values that increase by exactly 1 from one value to the next; its values do not have to be adjacent in nums.
Duplicate values do not increase a sequence's length, and the original ordering of nums does not matter. Return 0 if nums is empty. The algorithm must run in O(n) time, where n is the length of nums.
Example 1:
Input: nums = [14,9,11,10,13,15,15,2]
Output: 3
Explanation: The longest consecutive sequences are 9, 10, 11 and 13, 14, 15. Each has length 3; 12 is missing, so they cannot form one longer sequence.
Example 2:
Input: nums = [21,18,24,19,23,22,40,20]
Output: 7
Explanation: The values 18 through 24 are all present, forming a consecutive sequence of length 7.
Example 3:
Input: nums = []
Output: 0
Explanation: An empty array contains no values, so its longest consecutive sequence has length 0.
Constraints:
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9Each element of nums is an integer. may contain duplicate values.Need help or want more practice?