将c ++代码转换为javascript但返回不正确的结果

时间:2014-09-29 05:44:00

标签: javascript

将c ++代码转换为javascript,但返回的结果不正确。 c ++代码是here。以下是我的代码

    function CeilIndex(A, l, r, key) {
        var m;

        while( r - l > 1 ) {
            m = l + (r - l)/2;

            if (A[m] >= key) {
                r = m;
            } else {
                l = m;
            }
        }

        return r;
    }


    function LongestIncreasingSubsequenceLength(A, size) {
        var tailTable = new Array(size);
        var len;

        tailTable[0] = A[0];

        len = 1;

        for (var i = 1; i < size; i++) {
            if( A[i] < tailTable[0] ) {
                tailTable[0] = A[i];
            } else if( A[i] > tailTable[len-1] ) {
                tailTable[len++] = A[i];
            } else {
                tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i];
            }
        }

        return tailTable;
    }

    var A = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15];
    var n = A.length;
    console.log("Length of Longest Increasing Subsequence is: ",  LongestIncreasingSubsequenceLength(A, n));

当我执行上面的代码时,它返回Length of Longest Increasing Subsequence is: [0, 4, 2, 6, 1, 5, 3, 7, 15],而它的答案是[0, 2, 6, 9, 11, 15]

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

m在您的代码中变为双倍。所有数字在JS内部表示为双精度数。应该被截断为int,我猜? 以下代码似乎有效。

function CeilIndex(A, l, r, key) {
    var m;

    while( r - l > 1 ) {
        m = Math.floor(l + (r - l)/2);

        if (A[m] >= key) {
            r = m;
        } else {
            l = m;
        }
    }

    return r;
}