需要扭轉基於輸入數 例如整數數組扭轉的整數數組:需要基於輸入位數
Array be [1,2,3,4,5,6,7,8,9] and value of subset be N = 4
then the array after reversal will be [4, 3, 2, 1, 8, 7, 6, 5, 9].
if N = 3 then output should be [3,2,1,6,5,4,9,8,7]
無法與遞歸方法認爲適當的邏輯的或下面的java代碼任何循環概念
需要扭轉基於輸入數 例如整數數組扭轉的整數數組:需要基於輸入位數
Array be [1,2,3,4,5,6,7,8,9] and value of subset be N = 4
then the array after reversal will be [4, 3, 2, 1, 8, 7, 6, 5, 9].
if N = 3 then output should be [3,2,1,6,5,4,9,8,7]
無法與遞歸方法認爲適當的邏輯的或下面的java代碼任何循環概念
嘗試
public static int[] reverse(int[] a, int number) {
// negative case
if (number < 0) {
return a;
}
// higher count than array length
int size = number < a.length ? number : a.length;
int[] b = new int[size];
System.arraycopy(a, 0, b, 0, size);
for (int i = b.length - 1; i >= 0; i--) {
a[b.length - 1 - i] = b[i];
}
return a;
}
陣列具有與每個索引上述循環代碼元素簡單高效。
非常感謝。這是我尋找的。 – SurajSr
謝謝,你可以投我的答案 –
你會如何反轉整個數組(當N =數組長度時)? – Pshemo
N是索引還是數組中的值? – klutt
@klutt我認爲他需要扭轉所有的大小正好'4' –