我知道有移動陣列的解決方案。但是,沒有任何解決方案適合我。該代碼應實作以下目標:
該方法shift(int[] array, int places)接受 an array,將元素places- 向右移動,并將“剩余”元素替換為“0”。
到目前為止,我有:
public static int[] shiftWithDrop(int[] array, int places) {
if (places == 0 || array == null) {
return null;
}
for (int i = array.length-places-1; i >= 0; i-- ) {
array[i places] = array[i];
array[i] = 0;
}
return array;
}
這段代碼只能以某種方式作業,但它不會回傳所需的結果。我錯過了什么?
uj5u.com熱心網友回復:
這段代碼有幾個問題:
- 它回傳
null時places == 0-- 沒有移位,需要回傳原始陣列 - 在給定的回圈實作中,陣列的主要部分可能會被跳過,而不是
places用 0替換第一個元素,實際上陣列開頭的一些元素被設定為 0。
此外,最好更改方法的簽名以在 vararg 之前設定位置 array.
因此,為了解決這些問題,提供了以下解決方案:
public static int[] shiftWithDrop(int places, int ... array) {
if(array == null || places <= 0) {
return array;
}
for (int i = array.length; i-- > 0;) {
array[i] = i < places ? 0 : array[i - places];
}
return array;
}
測驗:
System.out.println(Arrays.toString(shiftWithDrop(1, 1, 2, 3, 4, 5)));
System.out.println(Arrays.toString(shiftWithDrop(2, new int[]{1, 2, 3, 4, 5})));
System.out.println(Arrays.toString(shiftWithDrop(3, 1, 2, 3, 4, 5)));
System.out.println(Arrays.toString(shiftWithDrop(7, 1, 2, 3, 4, 5)));
輸出:
[0, 1, 2, 3, 4]
[0, 0, 1, 2, 3]
[0, 0, 0, 1, 2]
[0, 0, 0, 0, 0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368777.html
上一篇:在圓形二維陣列中查找支點
