Location>code7788 >text

LeetCode128 Longest Continuous Sequence

Popularity:400 ℃/2024-11-09 16:20:00

longest continuous sequence

Title Link:LeetCode128

descriptive
Given an unsorted array of integers nums , find the length of the longest sequence of consecutive numbers (without requiring the elements of the sequence to be consecutive in the original array).

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

typical example

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation : The longest consecutive sequence of numbers is [1, 2, 3, 4]. Its length is 4.

reasoning

1. Use a hash table to store the numbers in the array.
2, traversing the hash table to find the current number of a number in front of whether there is, that is, num-1 in the hash table whether there is, if there is this number, then the current num is certainly not the longest continuous sequence of the first digit, directly skipped.
3, if it does not exist, then calculate the length of the consecutive sequences beginning with num, directly determine whether num + + exists, the existence of the length curLen + +.
4, will get the length of the continuous sequence and the length of the previous continuous sequence comparison, take the larger one, constantly update the length of the longest continuous sequence, and finally return.

coding

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int num : nums){
            (num);
        }
        int result = 0;
        for(int num : set){
            if(!(num-1)){
                int curLen = 0;
                int curNum = num;
                while((curNum++)){
                    curLen += 1;
                }
                result = (result,curLen);
            }
        }
        return result;
    }
}