2014-04-02 27 views
2

以下是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}

+0

這似乎是一個正確的問題。爲什麼downvote? – TechSpellBound

回答

3

你的算法是錯誤的。您正在檢查arr[i-1]是否不均勻,並用arr[i]替換它。如果arr[i]也很奇怪,那麼你不檢查它,即使它是奇數,它也會移動到前面。

你可以做的是

  • 找到數組中的第一偶數和與第一指數掉期,並增加索引。
  • 然後找到第二個偶數並用第二個索引交換它,直到數組結束。

變化的方法,如下圖所示:

public int[] moveEvenToFront(int[] arr){ 
    int temp=0; 
    int a=0; 
    for(int i=0;i<arr.length;i++){ 
     if(arr[i]%2==0){ 

      for (int j=i;j>a;j--){ 
       temp=arr[j-1]; 
       arr[j-1]=arr[j]; 
       arr[j]=temp; 
      } 
      a++; 
     } 
    } 
    return arr; 
} 
+0

感謝您的幫助。但按奇數順序存在一個小問題。它們的順序應與前一個數組中的順序相同。 –

+0

Oh..yeah..did沒有注意到...用新方法編輯了答案。 – anirudh

3

試試看直截了當:

public static Integer[] NUMBERS = {3,5,4,6,8,9,7,10}; 

public static void main(String[] args) { 
    ArrayList<Integer> ints = new ArrayList<>(Arrays.asList(NUMBERS)); 
    int nextIdx = 0; 
    for (int idx = 0; idx < ints.size(); idx++) { 
     if (ints.get(idx) % 2 == 0) ints.add(nextIdx++, ints.remove(idx)); 
    } 
    System.out.println(ints); 
} 

OUTPUT:

[4, 6, 8, 10, 3, 5, 9, 7] 
相關問題