Fork me on github

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;
    }
}
posted @ 2020-08-26 21:22  zjy4fun  阅读(172)  评论(0编辑  收藏  举报