java - 以下如何: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
解决方案
counts[x]++
将增加存在于x
数组索引处的数字counts
。
使用这些信息,应该很容易预测第一个 for 循环之后的值是什么。
推荐阅读
- node.js - 如何解决“错误:belongsTo 调用的东西不是 Sequelize.Model 的子类”?
- python - 切换 conda 环境需要我每次都输入 conda install tensorflow
- java - Flutter android许可接受错误
- react-native - 反应导航:使用向上滑动效果手动更改屏幕
- python - Autocad python - 从工具栏运行脚本
- python - 什么是用于删除列中所有文本的 python 正则表达式?
- algorithm - MT5 || MQL5 JYP 对交易不佳
- python - 如何将标记化的句子作为行附加到csv
- awk - 如何使用 awk 打印每列
- windows - 用于从 csv 文件的每一行中删除第一个和最后一个双引号的 Powershell 脚本