暴力循环在解决最长上升子序列问题时遇到的错误

对于一个数字序列,请设计一个复杂度为O(nlogn)的算法,返回该序列的最长上升子序列的长度,这里的子序列定义为这样一个序列U1,U2…,其中Ui < Ui+1,且A[Ui] < A[Ui+1]。

给定一个数字序列A及序列的长度n,请返回最长上升子序列的长度。

测试样例:

[2,1,4,3,1,5,6],7
返回:4

代码:

import java.util.*;
 
public class AscentSequence {
    public  int findLongest(int[] A, int n) {
        ArrayList<Integer> array=new ArrayList<>();
        for(int i=0;i<n;i++) {
            for(int k=1;k<=n-i;k++) {
                long temp=A[i];
                int upCount=1;
                for (int j = i + k; j < n; j++) {
                    if (A[j] > temp) {
                        temp = A[j];
                        upCount++;
                    }
                }
                array.add(upCount);
            }
        }
        int max=0;
        for(int a:array){
            if(a>max){
                max=a;
            }
        }
        return max;
    }
}

代码写完了,但运行时遇到了错误:
*
用例: [2,1,4,3,1,5,6],7
[203,39,186,207,83,80,89,237,247],9
[46,200,83,24,211,86,61,67],8
[157,232,6],3
[168,92,273,36,222,146],6
[93,215,6,231,210,19,119,271,232,31],10 [88181,66402,35219,85574,54640,5931,39028,9026,84648,15938,30692,58418,71423,21622,93420,17292,34854,10751,38335,82886,36348,28400,2471,60448,49691,20036,82783,24841,20614,63445,1709,43315,54001,73624,86913,40591,74500,73284,44309,45064,15469,63863,92843,94895,60988,17444,75657,84275,22532,88581,20936,77568,37370,27136,89450,5035,23390,22702,18417,33972,79610,20653,2679,28819,16866,36550,63695,22140,80453,43587,8584,8481,15002,76905,31585,75489,95860,10199,87114,9618,83500,44904,66773,95702,41138,64183,67206,71609,42960,48730,40095,91372,19423,60258,63186,91824,8348,54415,88171,67031,2624,23345,5942,22272,5199,63880,6056,52909,96552,96609,5982,40628,77770,23115,47054,76024,94235,15450,27757,43006,40548,45956,44692,40516,55014,89813,85578,53908,19730,19101,40903,8424,95014,83119,62573,20915,32664,54241,66608,50222,14763,85709,64582,29100,28508,59687,48399,6135,87663,41090,78091,9557,90518,46090,80111,71045,49494,15616,76865,83986,89947,88453,23572,47326,51668,2139,59913,10686,62417,19958,39883,83363,56714,1013,80694,52664,31553,80014,61391,47993,74636,7615,33191,53650,49487,59263,88850,1395,37726,8065,11606,41280,20268,41677,23021,41232,43455,78177,83498,20933,22404,16485,5413,64775,57113,79907,88067,11865,59772,65471,3547,42411,31588,54300,12270,14793,77373,60847,70908,39358,32083,65209,15846,53520,47948,63691,95868,17972,48689,8841,79841,53634,40624,11061,11218,13291,91543,28739,33361,127,87135],241
对应输出应该为: 4 5 3 2 2 4 25
你的输出为: 4 5 3 2 2 4 11
*

为什么这种暴力循环算法在遇到长度很大,数字很大的情况就会算错?

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值