以下是problem-如何將所有偶數移動到數組的前面?
鑑於整數作爲輸入數組,返回包含相同的號碼作爲輸入數組中的數組,但重新排列,使所有的偶數都在前面,勝算號碼在後面。請注意,偶數和奇數的順序應該保持不變,即如果在輸入偶數n2
之前出現偶數n1
,那麼在輸出數組n1
應該出現在n2
之前。奇數也是如此。另外請注意,在這個問題中,你不應該創建任何新的數組。
到目前爲止所做的事情如下,但我無法獲得預期的輸出。
public class MoveEvenToFront {
static int[] testcase1 = {3, 5, 4, 6, 8, 9, 7, 10};
public static void main(String[] args) {
MoveEvenToFront testInstance = new MoveEvenToFront();
int[] result = testInstance.moveEvenToFront(testcase1);
System.out.print("{");
for (int i = 0; i < result.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(result[i]);
}
System.out.print("}");
}
public int[] moveEvenToFront(int[] arr) {
int temp = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i - 1] % 2 != 0) {
temp = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = temp;
}
}
return arr;
}
}
預期輸出測試用例{1,2,3,4,5,6,7,8,10,12}
是{2,4,6,8,10,12,1,3,5,7}
。
這似乎是一個正確的問題。爲什麼downvote? – TechSpellBound