我正在尝试重新分配Integer数组。
目的是:我有一个数组,设为{2_000_000_000, 0}
。
我需要:
我的下面的代码:
for (int i = 0; i < data.size(); i++){ //Looking for max element
if (data.get(i) > max){ //of the array
max = data.get(i); //Save max element
index = i; //Save the index of max element
}
}
data.set(index, 0); //Set max element = 0
if (index == data.size()){ //In case of end of array
initPos = 0; //position is the beginning
}else {
initPos = index + 1; //If no the end - pos is the next
}
while (max > 0){ //This block of code looks have
if (initPos == data.size()){ //a small speed
initPos = 0;
}
int oldVal = data.get(initPos);
oldVal++;
data.set(initPos, oldVal);
max--;
initPos++;
}
所以问题是:代码while(max > 0)...
似乎运行缓慢。
我是否需要使用其他结构而不是ArrayList来加快分发过程?
答案 0 :(得分:1)
我将计算要分配给其他元素的数量,而不是循环max
次。
例如,使用伪代码:
data = { 0, 10, 42, 5, 3 };
max = 42; // you already calculated this, so in my example, I hardcode it.
index = 2; // same than above
data[index] = 0;
amountToDistribute = max / (data.length - 1); // 42 / 4 = 10.5, but it's floored to 10 since the division is made on integers
remaining = max % (data.length - 1); // 2 remaining
loop for i = 0 to i < data.length
{
if (i != index) // don't add to the max index
{
data[i] += amountToDistribute; //adding 10
}
}
// now let's add the 2 remaining
j = index + 1;
while (remaining-- > 0)
{
if (j >= data.length)
{
j = 0; //reset the iterator to 0 if the end was reached
}
data[j++]++; // add 1 to data[3] on first iteration, then to data[4] on the second one. It increases j too once added
}
print(data); // { 10, 20, 0, 16, 14 }
在我的示例中,您有42个可以重新分配给其他4个元素。
您不能为每个变量重新分配10.5(我想您只能使用整数)
然后,您将至少重新分配10个元素(由于整数是除法的,所以10.5的下限是10)。
用42 % 4
进行42模4运算,得到除法42 / 4
的其余部分,即2。剩下的2个以与您编写第一个算法相同的方式重新分配。
可以对其进行调整,因此所有操作将在1个循环中完成。但实际上它执行了7次迭代(第一个循环5次,第二个循环2次),而不是42次。
在该示例中,如果将{ 0, 10, 42, 5, 3 }
替换为{ 0, 10, 4000000000 (4 billions), 5, 3 }
,它将在5次迭代中产生相同的结果(每个元素增加10亿个元素,但最大一个元素),而不是算法中的40亿个