算法 - 求一个数组的最长递减子序列(C++)

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

/*
 * 求一个数组的最长递减子序列 - C++ - by Chimomo
 *
 * 题目: 求一个数组的最长递减子序列,比如{8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1}的最长递减子序列为{14,8,3,2,1}。
 *
 * Answer: Scan from left to right, maintain a decreasing sequence.
 * For each number, binary search in the decreasing sequence to see whether it can be substituted.
 */

#include <iostream>
#include <cassert>
#include <stack>

using namespace std;

int BinarySearch(const int *A, int nTarget, int nLen);

/**
 * Find the longest decreasing sequence in array A of length nLen.
 * @param A The array.
 * @param nLen The array length.
 */
void FindLongestDecreasingSequence(int *A, int nLen) {
    int *index = new int[nLen];
    int *LDS = new int[nLen];
    index[0] = A[0];
    LDS[0] = 1;
    int indexLen = 1;

    for (int i = 1; i < nLen; i++) {
        int pos = BinarySearch(index, A[i], indexLen);
        index[pos] = A[i];
        LDS[i] = pos + 1;
        if (pos >= indexLen) {
            indexLen++;
        }
    }

    int ResultLen = indexLen;

    for (int i = nLen; i >= 0; i--) {
        if (LDS[i] == ResultLen) {
            index[ResultLen - 1] = A[i];
            ResultLen--;
        }
    }

    for (int i = 0; i < indexLen; i++) {
        cout << index[i] << " ";
    }

    delete[] index;
}

/**
 * Binary search nTarget in array A of length nLen.
 * @param A The array.
 * @param nTarget The target.
 * @param nLen The array length.
 * @return The position.
 */
int BinarySearch(const int *A, int nTarget, int nLen) {
    assert(A != nullptr && nLen > 0);
    int start = 0;
    int end = nLen - 1;

    while (start <= end) {
        int mid = (start + end) / 2;

        if (nTarget > A[mid]) {
            end = mid - 1;
        } else if (nTarget < A[mid]) {
            start = mid + 1;
        } else {
            return mid;
        }
    }

    return start;
}

int main() {
    int A[] = {8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1};
    int nLen = sizeof(A) / sizeof(int);
    FindLongestDecreasingSequence(A, nLen);
    return 0;
}

// Output:
/*
14 8 7 6 2 1
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值