【发布时间】:2020-04-27 20:31:29
【问题描述】:
我有一个计数器变量数组(全部初始化为 0)。我有 k 条指令需要在阵列上运行。一条指令包括在起始索引和结束索引(包括两者)之间递增数组的所有值。
例如:
n = 5, k = 2
arr = [0,0,0,0,0]
0,2 - (arr = [1,1,1,0,0])
0,1 - (arr = [2,2,1,0,0])
最后我需要按计数值的降序对它进行排序,这很容易。
我正面临编写代码以低于 O(n^2) 时间复杂度来执行此操作的问题。我必须使用两个循环。
Array counts = [0,0,0,0... n times]
for(Instruction instruction:instructions){
int start = instruction.start;
int end = instruction.end;
for(i=start;i<=end;i++){
counts.set(i,counts.get(i)+1);
}
}
有什么方法可以更快地完成吗?我也可以删除计数数组并采用实现此目的所需的任何数据结构。
【问题讨论】:
-
指令是由somthing订购的吗?
-
目前是随机的。如果它使一切更快,可以根据您的方便订购
标签: performance data-structures time-complexity