zoukankan      html  css  js  c++  java
  • Leetcode 128.最长连续序列

    最长连续序列

    给定一个未排序的整数数组,找出最长连续序列的长度。

    要求算法的时间复杂度为 O(n)

    示例:

    输入: [100, 4, 200, 1, 3, 2]

    输出: 4

    解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

     1 class Solution{
     2     public int longestConsecutive(int[] nums){
     3         if(nums.length<=0){
     4             return 0;
     5         }
     6         Set<Integer> numSet=new HashSet<>();
     7         for(int n:nums){
     8             numSet.add(n);
     9         }
    10         int max=0;
    11         for(int n:nums){
    12             numSet.add(n);
    13         }
    14         for(int n:nums){
    15             int consecutive=1;
    16             int next=n+1;
    17             while(numSet.contains(next)){
    18                 numSet.remove(next);
    19                 next=next+1;
    20                 consecutive++;
    21             }
    22             int pre=n-1;
    23             while(numSet.contains(pre)){
    24                 numSet.remove(pre);
    25                 pre=pre-1;
    26                 consecutive++;
    27             }
    28             max=max<=consecutive?consecutive:max;
    29         }
    30         return max;
    31     }
    32 }
  • 相关阅读:
    Linux删除文件相关命令
    Bing语句
    VS2013配置Winpcap
    node10-mongoose
    node09-cookie
    node08-express
    node07-http
    node06-path
    node05-fs
    node04-buffer
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10187811.html
Copyright © 2011-2022 走看看