[Likou] 128. The longest continuous sequence<Hash, Set>

[Likou] 128. The longest continuous sequence

Given an unsorted integer array 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 an algorithm with time complexity of O(n) 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]. Its length is 4.

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

提示:
0 <= nums.length <= 1 0 5 10^5 105
- 1 0 9 10^9 109 <= nums[i] <= 1 0 9 10^9 109

answer

Consider enumeration: x, see if it has x+1, x+2, x+3...
During the enumeration process, if you enumerate 3…, because it’s not the longest.
Consider that during enumeration, the x obtained does not have x-1, that is, a number without a predecessor. (Hash to determine whether there is a predecessor number, and then enumerate one by one)

class Solution {
    
    
    public int longestConsecutive(int[] nums) {
    
    
    	// 去重
        Set<Integer> num_set = new HashSet<Integer>();

        for (int num : nums) {
    
    
            num_set.add(num);
        }

        int longesLength = 0;

        for (int num : num_set) {
    
    
            // set 中没有 num-1,说明不构成连续子序列
            if (!num_set.contains(num - 1)) {
    
    
                int currentNum = num;
                int currentLength = 1;
				
				//枚举当前这个数(没有前驱),x能+到几就是多长
                while (num_set.contains(currentNum + 1)) {
    
    
                    currentNum += 1;
                    currentLength += 1;
                }
				// 每找到一个数(没有前驱),更新最长的
                longesLength = Math.max(longesLength, currentLength);
            }
        }
        return longesLength;
    }
}

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/133174109
Recommended