LeeCode (hash table) 128_ longest continuous sequence

LeeCode (hash table) 128_ longest continuous sequence

Problem:
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).

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

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/longest-consecutive-sequence The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving ideas:
hash table

  1. First use set to remove weight
  2. Then traverse each number num in the set to determine whether there is a predecessor (that is, there is num-1). If there is a predecessor, skip it, because if num has a predecessor, the longest sequence found with num as the starting point will definitely be better than num -1 is the length of the longest sequence found at the starting point less than 1 length.
  3. Find the longest continuous sequence of the starting point and determine which is longer than the current longest continuous sequence.

Java code:

import java.util.HashSet;
import java.util.Set;

public class 最长连续序列 {
    
    
	public int longestConsecutive(int[] nums) {
    
    
		Set<Integer> num_set = new HashSet<Integer>();
		for(int num : nums){
    
    
			num_set.add(num);
		}
		
		int longest = 0;
		
		for(int num : num_set){
    
    
			if(!num_set.contains(num-1)){
    
    
				int cur_num = num;
				int length = 1;
				
				while(num_set.contains(cur_num+1)){
    
    
					length++;
					cur_num++;
				}
				
				longest = Math.max(length, longest);
			}
		}
		return longest;	
	}
}

Guess you like

Origin blog.csdn.net/u013456390/article/details/112062301
Recommended