首页 > 解决方案 > 以下如何:arrayName[x]++; 工作,它在以下情况下输出什么?

问题描述

有一个名为 的程序countingSort,它的一段代码如下所示,它a通过计算每个数字在 中出现的次数来处理整数数组a,然后使用计数将 的元素分配给a结果数组result以确定它们的位置。

// returns a sorted copy of a, assuming that it contains
// only integers in the range 0 .. k-1
public static int[] countingSort(int[] a, int k)
{
    int[] counts = new int[k];
    for (int x : a)
    {
        counts[x]++;
    }
    ...

我感到困惑的是线路的运作counts[x]++。我见过双加号用作增量,但在这种情况下从未见过。我想解释一下应用程序是如何处理的,特别是上面给出的循环结束后countingSort({3,7,1,3,8,2,1}, 10)数组的状态。counts[]

这是上下文的完整代码:

// returns a sorted copy of a, assuming that it contains
// only integers in the range 0 .. k-1
public static int[] countingSort(int[] a, int k)
{
    int[] counts = new int[k];
    for (int x : a)
        counts[x]++;
    int total = 0;
    for (int i = 0; i < k; i++)
    {
        int oldCount = counts[i];
        counts[i] = total;
        total += oldCount;
    }
    int[] result = new int[a.length];
    for (int x : a)
    {
        result[counts[x]] = x;
        counts[x]++;
    }
    return result;
}

counts[x]++同样,在第三个for循环中再次使用同一行。

所以基本上,我有两个问题;

线路的功能是什么,counts[x]++它是如何工作的?

给定要处理的应用程序是,第一个循环结束时数组countingSort({3,7,1,3,8,2,1}, 10)的状态是什么?counts[]for

标签: javaarrays

解决方案


counts[x]++将增加存在于x数组索引处的数字counts

使用这些信息,应该很容易预测第一个 for 循环之后的值是什么。


推荐阅读