leetcode hot 07

解题思路:因为可能存在相同的数,所以运用到HashSet去重,然后遍历hashset每个数num,如果num-1不在hashset中,那么num就是序列开头,然后继续查找num++,直到hashset中找不到为止,记录长度,最后取最长的长度。

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> hashset = new HashSet<>();
        int maxlength = 0;
        for(int num:nums) hashset.add(num);
        for(int num:hashset){
            if(!hashset.contains(num-1)){
                int i = 0;
                while(hashset.contains(num+i)){
                    i++;
                }
                // if(i>maxlength) maxlength=i;
                maxlength = Math.max(i,maxlength);
            }
        }
        return maxlength;
    }
}
posted @ 2025-02-20 19:55  kukudev  阅读(7)  评论(0)    收藏  举报