私は、このような単純な文脈では、もっと複雑な説明が余分にあるので、コードにコメントしました。
//Scan all the cities, from i = 0 to i = index -1
for (int i = 0; i < index; i++)
{
//Check it cities[i] has LESS population than specified
if (cities[i].getPopulation() < population)
{
//We need to remove cities[i]
//We shift all the subsequent cities
//(cities[i+1], cities[i+2], ... cities[index-1] one position LEFT,
//thereby overwriting cities[i] and so deleting it
//Shift all the subsequent cities left
//We start this for FROM i, so the first iteration is
//cities[i] = cities[i + 1];
//The second is
//cities[i + 1] = cities[i + 2];
//and so on. We STOP AT index - 2 (note the strict less than)
//So that j + 1 is AT MOST index - 1
for (int j = i; j < index - 1; j++)
{
cities[j] = cities[j + 1];
}
//Since j was at most index - 2, the cities[index - 1] was not
//overwritten with the next one. Naturally as there is no next one
//for it.
//This last city is now duplicated (the copy is at index - 2) and
//Must be overwritten with null.
//Also index, which keep track of the number of cities must be
//decremented (here the pre-decrement -- is used)
cities[--index] = null;
//cities[i] was the deleted city. But now it contains cities[i + 1]
//Which is a totally different city!
//If we continue the for now, we will go to the NEXT city, as i
//will be incremented, to keep i the same one more iteration, we
//decrement it. This way we process (the new) cities[i] one more time.
i--;
}
}
アルゴリズムを完全に理解するまで、古いペンシルとゴムを使用してください。本当に良い方法はありません。
いいえ、このメソッドは、指定された制限の下にある人口を持つすべての都市を削除します。ちなみに、それは非常に非効率的な方法(O(N²))で行われ、禁止されるべきです。 –
Lolとこのメソッドをどのようにコード化しますか? –
単一のループで、すべての保持された要素を左にパックします。 –