• 求数组中包含的最长子序列


    问题描述:

    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:          }
  • 相关阅读:
    【转载】Java反射: 数组
    【转】Maven3把命令行创建的web工程转成Eclipse和IntelliJ Idea的工程
    (转载)Sumblime Text 2 常用插件以及安装方法
    [转]h5页面测试总结
    maven学习讲解
    struts2权威指南学习笔记:struts2引入自定义库
    《Struts2.x权威指南》学习笔记2
    《Struts2.x权威指南》学习笔记1
    secureCRT 如何上传下载文件
    zabbix 4.2 发送警告邮件Python脚本
  • 原文地址:https://www.cnblogs.com/xubenben/p/3381786.html
Copyright © 2020-2023  润新知