Likou-Hash-The longest continuous sequence

topic

Given an unsorted array of integers  nums , find the length of the longest sequence of consecutive numbers (the sequence elements are not required to be consecutive in the original array).

Please design and implement  O(n) an algorithm with time complexity to solve this problem.

Example 1:

**Input: **nums = [100,4,200,1,3,2]
**Output: **4
**Explanation: **The longest continuous sequence of numbers is[1, 2, 3, 4]。它的长度为 4。

Example 2:

**Input: **nums = [0,3,7,2,5,8,4,6,0,1]
**Output: **9

hint:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109

Ideas

The characteristics of this question can be summarized in one sentence. Use a number as the key, and use the maximum continuous length of the current number as the value. Take num-1 and num+1 each time to check whether there is a length. If not, set it to 0. If there is, set it to 0. left and right, the new length is left+right+1 and the value of the hash table under the left and right boundaries is updated at the same time, that is, hash[left - length] hash[right+length] = length, and the longest Length is returned after one pass.

Guess you like

Origin blog.csdn.net/TongOuO/article/details/132522655
Recommended