algorithm - 该算法对于查找最长递增子序列是否正确?

标签 algorithm

我收到一个未排序的数组,我需要找到最长的递增子序列。根据Wikipedia最有效的算法是 O(nlogn) 而这是 O(n) 所以我肯定在做一些愚蠢的错误

public static int[] longestAscending(int[] arr) {
        // {x /* starting index */, y /* ending index */};
        int[] max = {0, 0};
        int[] current = {0,1};

        for (int i=1; i<arr.length; i++) {
            if (arr[i-1] < arr[i]) {
                current[1]++;
                if (current[1] - current[0] > max[1] - max[0]) {
                    max[0] = current[0];
                    max[1] = current[1];
                }
            } else {
                current[0] = i;
                current[1] = i + 1;
            }
        }

        return max;
    }

最佳答案

您的算法只检测连续的子序列,不检测有间隙的子序列。例如:

1 9 2 3

此处最长的递增子序列是 1 2 3,您的算法找不到。

关于algorithm - 该算法对于查找最长递增子序列是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29067188/

相关文章:

algorithm - 用多项式大小 bool 表达式表达事实

algorithm - 多项式表达式加权的前缀和,你能做得更快吗?

algorithm - 线性搜索的循环不变量

algorithm - 蒙特卡洛树搜索算法中的转置表对 UCT 分数的意外影响

arrays - 左/右旋转数组后最长递增子数组的长度

algorithm - 使用 : system time() 执行 R 代码

PHP如何遍历分层平面数组?

algorithm - 使用流程图识别三角形

algorithm - 在 o(1) 中生成一个集合的所有组合

r - 如何找到两个值的组合,使它们的比率和总和固定为 R 的某些数字