zoukankan      html  css  js  c++  java
  • 求数组中包含的最长子序列

    问题描述:

    Given an int array which might contain duplicates, find the largest subset of it which form a sequence.
    Eg. {1,6,10,4,7,9,5}
    then ans is 4,5,6,7

    解答:线性时间,空间为常数(该数组中最大元素的值)

    算法:

       1:  public int[] longestConsecutiveSequence(int[] a) 
       2:          {
       3:                  int first = Integer.MAX_VALUE; // the first number of the maximum consecutive sequence
       4:                  int length = 0; // the length of the maximum consecutive sequence
       5:                  Map<Integer, Integer> table = new HashMap<Integer, Integer>();
       6:                  for(int i: a) {
       7:                          if(!table.containsKey(i)) {
       8:                                  int start = i;
       9:                                  int end = i;
      10:                                  if(table.containsKey(i + 1) && table.get(i + 1) >= i + 1) {
      11:                                          end = table.get(i + 1);
      12:                                          table.remove(i + 1);
      13:                                          table.remove(end);
      14:                                  }
      15:                                  if(table.containsKey(i - 1) && table.get(i - 1) <= i - 1) {
      16:                                          start = table.get(i - 1);
      17:                                          table.remove(i - 1);
      18:                                          table.remove(start);
      19:                                  }
      20:                                  table.put(start, end);
      21:                                  table.put(end, start);
      22:                                  if(end - start + 1 > length) {
      23:                                          first = start;
      24:                                          length = end - start + 1;
      25:                                  }
      26:                          }
      27:                  }
      28:                  System.out.println(table);
      29:                  System.out.println(length);
      30:                  int[] s = new int[length];
      31:                  for(int i = 0; i < length; i++) s[i] = first + i;
      32:                  return s;
      33:          }
  • 相关阅读:
    增加samba用户提示Failed to add entry for user
    二叉树
    excel技巧
    mongodb导入json文件
    mongodb导出数据csv格式
    mongoexport导出csv中文乱码
    左连接,结果大于左面的表验证 解释
    plsql 用法和技巧
    对javaNI和NIO理解
    TinyMCE4.x整合教程-Xproer.WordPaster
  • 原文地址:https://www.cnblogs.com/xubenben/p/3381786.html
Copyright © 2011-2022 走看看