zoukankan      html  css  js  c++  java
  • 【模式匹配】— 求比数组所有比自身元素小且在它之前离它最近的元素位置,时间复杂度O(n).

    package basic;
    
    public class NextGen {
    
     /**
      * 实际上就是迭代正向子结构Next数组的变形
      */
     public static void main(String[] args) {
      
      int[] c = {13,43,4,65,12,34,12,5,90,123,54,72,99,22,18,7,9,1,58,93};
      int[] a = new int[c.length];
      a[0] = -1;
      int i = -1;
      for(int j = 1 ; j < c.length ; j++){
       i = j - 1;
       if(c[j] > c[i]){
        a[j] = i;
       }else{
        i = a[i];
        while(i >= 0 && c[j] <= c[i]){
         i = a[i];
        }
        if(i >= 0 && c[j] > c[i])
         a[j] = i;
        else
         a[j] = -1;
       }
      }
      
      for(int i1 = 0 ; i1 < c.length ; i1++){
       if(a[i1] >= 0)
        System.out.println("比" + c[i1] + "小且在它之前离它最近的元素位置为" + a[i1] + "值为" + c[a[i1]]);
       else
        System.out.println("比" + c[i1] + "小且在它之前离它最近的元素不存在");
      }
      System.out.println();
     }
    
    }
  • 相关阅读:
    StopAllSounds
    GotoAndPlay
    区间(interval)
    因数(factor)
    [HAOI2009]逆序对数列
    生物分子gene
    数轴line
    [SCOI2008]配对
    精力(power)
    bzoj4987: Tree(树形dp)
  • 原文地址:https://www.cnblogs.com/lixusign/p/2714788.html
Copyright © 2011-2022 走看看