LeetCode-128. Longest consecutive sequence

  1. Longest contiguous sequence

Title description

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

Advanced: Can you design and implement a solution with a time complexity of O(n)?

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

Problem-solving ideas

Prepare a HashSet, put all the elements into the set, and then traverse each number num in the array

  • If num-1 exists in the set, then num cannot be the left boundary, skip directly
  • If num-1 does not exist in the set, then num will be a left boundary. We will continue to find whether num+1, num+2... exist in the set to see how many continuous sequences with num as the left boundary are. long
class Solution_128 {
    
    
    /**
     * 准备一个HashSet,将所有元素入set,之后遍历数组中的每一个数num
     *  如果num - 1存在于set中,那么num不可能是左边界,直接跳过
     *  如果num - 1 不存在set中,那么num会是一个左边界,我们再不断查找num + 1,num + 2....是否存在于set中,来看以num为左边界的连续序列能有多长
     * @param nums
     * @return
     */
    public int longestConsecutive(int[] nums) {
    
    
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
    
    
            set.add(num);
        }
        int res = 0;
        for (int num : nums) {
    
    
            if (set.contains(num - 1))
                continue;
            else {
    
    
                //len记录以num为左边界的连续序列的长度
                int len = 0;
                while (set.contains(num++))
                    len++;
                res = Math.max(res,len);
            }
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_35655602/article/details/115057212