gpt4 book ai didi

java - 下面的: arrayName[x]++; work and what does it output in the following context?怎么办

转载 作者:行者123 更新时间:2023-12-01 07:18:07 25 4
gpt4 key购买 nike

有一个名为countingSort的程序,下面列出了其中的一段代码,它通过计算每个数字出现的次数来处理整数数组aa 中,然后使用计数将 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;
}

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

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

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

假设要处理的应用程序是 countingSort({3,7,1,3,8,2,1}, 10) 的状态是什么counts[] 数组位于第一个 for 循环的末尾?

最佳答案

counts[x]++ 将增加数组 counts 索引 x 处的数字。

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

关于java - 下面的: arrayName[x]++; work and what does it output in the following context?怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com