这是创新工厂的一道面试题:求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
我在做这个题时遇到一个关于数据边界问题,以下是程序代码:
public class Questions {
         public static void main(String args[]){
          int []groap={8,5,4,8,12,9,15,5};
          int i=0,j;
          for(i=0;i<8;i++){
          for(j=i;j<8;j++){
          if(groap[i]<groap[j+1]){
          int temp=groap[i]; groap[i]=groap[j+1]; groap[j+1]=temp;
          }
          }
          }
          for(i=0;i<8;i++){
          System.out.print(groap[i]+"  ");
          if(groap[i]==groap[i+1])
          i++;
          }
          System.out.println("");
         }
}
这样运行时出现异常,无法输出结果。我很奇怪,我的数据里面是8个元素,我在for()里面写个8为什么会出一场呢?而我把8改为7后可以运行出结果,但还会出现同样的异常。恳请各路高手帮忙解答,不胜感激!

解决方案 »

  1.   

    groap[i]<groap[j+1]..................
    当你是7的时候不就越界了??
    这么简单的问题自己多debug一下。。
      

  2.   


    //一个for行了    public static void main(String args[]) {
            int[] groap = {9, 4, 3, 2, 5, 4, 3, 2};
            int i = 0, sp = 0, sl = 1, np = 0, nl = 1;
            for (i = 1; i < groap.length; i++) {
                if (groap[i] < groap[i - 1]) {//如果等于也算的话,这里变成 <=
                    nl++;
                } else {
                    if (nl > sl) {
                        sp = np;
                        sl = nl;
                        np = i;
                        nl = 1;
                    }
                }
            }
            System.out.println("输出:");
            for (i = 0; i < sl; i++) {
                System.out.print(groap[sp + i] + " ");
                if (groap[i] == groap[i + 1]) {
                    i++;
                }
            }
            System.out.println("");
        }
      

  3.   

    改成这样试试吧。 
    for(i=0;i<8;i++){
      for(i=0;j<i;j++){
      if(groap[j]<groap[j+1]){
      int temp=groap[j]; groap[j]=groap[j+1]; groap[j+1]=temp;
      }
      }
      }