LeetCode-128 最长连续序列

LeetCode-128 最长连续序列

class Solution {
    public int longestConsecutive(int[] nums) {
       Set<Integer> set = new HashSet<Integer>();
       int length = nums.length;
       for(int i=0;i<length;i++)
          set.add(nums[i]);
       int maxConsecutive = 0;
       int nowConsecutive = 0;
       for(int num:set){  // set 去重可以快很多
           if(set.contains(num - 1))
              continue;
            else
            {
                 nowConsecutive = 1;
                 int add = 1;
                 while(set.contains(num + add)){
                     nowConsecutive += 1;
                     add += 1;
                 }
                maxConsecutive = Math.max(maxConsecutive,nowConsecutive);
            }
       }
       return maxConsecutive;
    }
}
上一篇:128. 最长连续序列


下一篇:4.类型转换