keer哥的点点滴滴

人生格言 为民族立生命,为万世开太平!——连战

算法思想:待找最长递增子序列数组为A,设一个辅助数组B,辅助数组B中i位置存放的是A中以该元素为结尾元素的递增子序列长度为i的元素。比如A={8,9,1,4,5},则有B={-10000,8,9,}
                                                           {            ,1,4,}
                                                           {            ,  , ,5}
不难看出,B数组的最大长度是length(A)+1,而就在我们遍历A数组的过程中,我们试图将当前遍历到的A数组中的元素A[i]插入到B数组中去,同时,也容易看出,在B数组中有效长度内的元素是单调递增的,这个有详细证明,而我们最后所要求得的最大递增子序列的长度就是B数组的有效长度-1(出去B[0]元素)。

/**
  * @param array the array which contains the number sequence.
  * @return the length of the longest increasing subsequence of the array.
  */
 public int longestIncreasingSubsequenceLength(int array[]){
  int n = array.length; // array's length.
  /**
   * 定义一个数组,数组中元素B[i]是在<code>array</code>以B[i]元素为结尾数字
   * 的当前子数字序列长度为i的最小的数字。此数组有个性质,就是单调递增。
   */
  int B[] = new int[n+1];
  /**
   * 定义最大数——无穷大数
   */
  int INF = 10000000;
  /**
   * 当前所求得的最大子序列长度
   */
  int length = 1;
  B[0] = -INF;
  /**
   * 初始化
   * 子序列长度为1的当前最小数字肯定是array[0]
   */
  B[1] = array[0];
  
  for(int i=1;i<n;i++){
   int head,tail,median;
   head = 0;
   tail = length;
   /**
    * 查找array[i]这一数字在B数组中应该存放的位置
    */
   while(head<=tail){
    median = (head+tail)/2;
    if(B[median]<array[i]){
     head = median+1;
    }else{
     tail = median-1;
    }
   }
   B[head] = array[i];
   /**
    * 如果array[i]存放的位置的index比当前所得的length还大的话,
    * 说明已经找到更长的子序列,则长度等于该index
    */
   if(head>length) length = head;
  }
  return length;
 }
posted on 2007-09-19 13:47  珂儿  阅读(1406)  评论(4编辑  收藏  举报