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();
 }

}

 

posted on 2012-10-08 09:51  真心的不懂  阅读(261)  评论(0编辑  收藏  举报