public Ranking(String [] names,float [] scores){ nameTest = new Cities [names.length]; rankTest = new Cities [names.length]; city = new Cities [names.length]; scoreRanks = new Float [scores.length];對於(int i = 0; i < scores.length - 1; i ++){ if(scores [i] == scores [i + 1]) throw new IllegalArgumentException(); } if(names == null || scores == null) throw new NullPointerException(); if(names.length!= scores.length) throw new IllegalArgumentException();降低產生秩數陣列的時間複雜度
for (int p = 0; p < scoreRanks.length; p++) {
scoreRanks[p] = scores[p];
}
int[] ranking = new int[names.length];
for (int k = 0; k < ranking.length; k++) {
ranking[this.smallestIndex()] = k + 1;
}
for (int i = 0; i < ranking.length; i++) {
city[i] = new Cities(names[i], ranking[i]);
nameTest[i] = new Cities(names[i], ranking[i]);
rankTest[i] = new Cities(names[i], ranking[i]);
}
Arrays.sort(nameTest, Cities.BY_NAME);
Arrays.sort(rankTest, Cities.BY_RANK);
for (int i = 0; i < names.length - 1; i++) {
if (nameTest[i].getName().equals(nameTest[i + 1].getName())
|| nameTest[i].getName() == null
|| rankTest[i].getRank() == rankTest[i + 1].getRank())
throw new IllegalArgumentException();
}
}
public int smallestIndex() {
float smallest = 0.0f;
int i;
for (i = 0; i < scoreRanks.length; i++) {
if (scoreRanks[i] > 0.0f) {
smallest = scoreRanks[i];
break;
} else
continue;
}
int j = 1;
while (j < scoreRanks.length) {
if (scoreRanks[j] < smallest && scoreRanks[j] != 0.0f) {
smallest = scoreRanks[j];
i = j;
}
j++;
}
scoreRanks[i] = 0.0f;
return i;
}
這是我的排名構造函數。目前,for循環內的smallestIndex()調用會將其調高到O(n^2)時間,但我需要它在不超過O(n log n)時間內運行。
這是做什麼是一個分數和名稱的數組。然後,LOWEST分數爲1,次低爲2,依此類推。然後,我可以創建名稱[i]與排名[i]相對應的城市對象。
希望是有道理的。買耶我沒有得到我能做的,以獲得相同的結果,但在O(n日誌n)時間。我的代碼完美的作品,它實在是太慢了我想:(。
另外,將O(2N日誌N + 5N)歸結爲爲O(n log n)的?
1.什麼是原始問題? 2.是的,'O(2n log + 5n)= O(n logn)' –