128 最长连续序列

思路:找序列中最小的那个数字,然后递增检查。

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

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int a : nums){
            set.add(a);
        }
        
        int maxLen = 0;
        for(int a : set){
            if (!set.contains(a - 1)) {
                int cur = 1;
                a++;
                while(set.contains(a)){
                    cur++;
                    a++;
                }
                maxLen = Math.max(maxLen, cur);
            }
        }
        
        return maxLen;
    }
}
原文地址:https://www.cnblogs.com/realzhaijiayu/p/13567955.html