zoukankan      html  css  js  c++  java
  • Longest Consecutive Sequence

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

    For example,
    Given [100, 4, 200, 1, 3, 2],
    The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

    Your algorithm should run in O(n) complexity.

    思路

    先对数组排序,然后用DP

     1 public class Solution {
     2     public int longestConsecutive(int[] num) {
     3         Arrays.sort(num);
     4         int curLength = 1;
     5         int maxLength = 1;
     6         
     7         for(int i = 1; i < num.length; i++){
     8             if(num[i] == num[i - 1])
     9                 continue;
    10             else if(num[i] - num[i - 1] == 1){
    11                 curLength ++;
    12                 maxLength = maxLength > curLength ? maxLength : curLength;
    13             }
    14             else
    15                 curLength = 1;
    16         }//for
    17         
    18         return maxLength;
    19     }
    20 }

     上面思路时间复杂度为O(N*logN)

    题目要求用O(n)这里可以借助hashtable或者hashmap,先将数组全部放到hash表中,在遍历数组,找到前面和后面的数,这里利用了hash通过get方法时间复杂度为o(1)

     1 import java.util.Hashtable;
     2 
     3 public class Solution {
     4     public int longestConsecutive(int[] num) {
     5         Hashtable<Integer, Integer> map = new Hashtable<Integer, Integer>();
     6         for(int i = 0; i < num.length; i++){
     7             map.put(num[i], 1);
     8         }//放到hash表中
     9         
    10         int result = 0;
    11         for(int i = 0; i < num.length; i++){
    12             int sum = 1;
    13             if(map.get(num[i]) != null){
    14                 int left = num[i] - 1;
    15                 map.remove(num[i]);
    16                 while(map.get(left) != null){
    17                     sum ++;
    18                     map.remove(left);
    19                     left--;
    20                 }//while
    21                 int right = num[i] + 1;
    22                 while(map.get(right) != null){
    23                     sum++;
    24                     map.remove(right);
    25                     right++;
    26                 }//while
    27                 
    28                 result = result > sum ? result : sum;
    29             }//if
    30         }//for
    31         
    32         return result;
    33     }
    34 }
  • 相关阅读:
    Oracle中常见的33个等待事件小结
    DATAGUARD中手工处理日志v$archive_GAP的方法
    ORACLE 如何定位消耗资源的SQL
    ORACLE 全局索引和本地索引
    Oracle中获取执行计划的几种方法分析
    BUFFER CACHE之主要的等待事件
    查看tablespace实际使用量和剩余空间
    Linux环境配置文件的理解
    Shell 传递参数
    Linux开局配置注意事项
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4248340.html
Copyright © 2011-2022 走看看