簡體   English   中英

這個C ++函數與等效的Java函數有何不同?

[英]How is this C++ function working differently than the equivalent java function?

我正在嘗試實現以下C ++算法的Java版本:

void constructPrintLIS(int arr[], int n)
{
    std::vector< std::vector<int> > L(n);

    L[0].push_back(arr[0]);

    for (int i = 1; i < n; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if ((arr[i] > arr[j]) &&
                (L[i].size() < L[j].size() + 1))
            {
                L[i] = L[j];
                cout << true << endl;
            }
            else
            {
                cout << false << endl;
            }
        }

        L[i].push_back(arr[i]);
    }

    std::vector<int> max = L[0];

    for (std::vector<int> x : L)
    {
        if (x.size() > max.size())
        {
            max = x;
        }
    }

    printLIS(max);
}

這是Java版本

private static List<Integer> getLongestIncreasingSubsequence(
        List<Integer> sequence
        )
{   
    ArrayList<ArrayList<Integer>> cache = 
            new ArrayList<ArrayList<Integer>>(sequence.size());
    // Populate the elements to avoid a NullPointerException
    for(int i = 0; i < sequence.size(); i++)
    {
        cache.add(new ArrayList<Integer>());
    }
    cache.get(0).add(sequence.get(0));

    // start from the first index, since we just handled the 0th
    for(int i = 1; i < sequence.size(); i++)
    {
        // Add element if greater than tail of all existing subsequences
        for(int j = 0; j < i; j++)
        {
            if((sequence.get(i) > sequence.get(j)) 
                    && (cache.get(i).size() < cache.get(j).size() + 1))
            {
                cache.set(i, cache.get(j));
            }
        }
        cache.get(i).add(sequence.get(i));                  
    }

    // Find the longest subsequence stored in the cache and return it
    List<Integer> longestIncreasingSubsequence = cache.get(0);
    for(List<Integer> subsequence : cache)
    {
        if(subsequence.size() > longestIncreasingSubsequence.size())
        {
            longestIncreasingSubsequence = subsequence;
        }
    }
    return longestIncreasingSubsequence;
}

我不明白我在做什么。 當測試序列為{9766, 5435, 624, 6880, 2660, 2069, 5547, 7027, 9636, 1487}時,C ++算法將打印正確的結果,正確的結果為624, 2069, 5547, 7027, 9636 但是,我編寫的Java版本返回的錯誤結果為624, 6880, 2660, 2069, 5547, 7027, 9636, 1487我不明白為什么。 我嘗試在調試器中跟蹤它,但無法弄清楚出了什么問題。

我嘗試添加一條打印語句,該語句指示if語句是否每次均評估為true / false,並將其與C ++程序進行比較,結果是相同的,所以這不是問題。

我懷疑這與向量和ArrayList之間的細微差別有關,但我不知道。

我懷疑問題是在Java中,緩存包含對列表的引用 ,而在C ++中,它包含列表本身。

因此,在C ++中

L[i] = L[j];

將索引j處的列表復制到索引i ,而在Java中

cache.set(i, cache.get(j));

復制參考。 這意味着,當您隨后將項目添加到一個項目時,它們也會同時添加到另一個項目。

也許用

cache.set(i, new ArrayList<>(cache.get(j)));

這樣就可以像在C ++中那樣創建副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM