905. Sort Array By Parity

leetcode 上面有900多道題了?java

905. Sort Array By Parity數組

題意:給定一個一維數組,將數組中的偶數移動到數組的首部,奇數放在數組的尾部。指針

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

一看就知道用雙指針。一個在數組頭,一個在數組尾。左邊的指針判斷指向的值是不是奇數,是就判斷右邊指針是不是偶數。當左指針知足奇數,同時右指針知足偶數時,交換兩邊的值。若是左指針的值不是奇數,則+1.若是右邊的指針不是偶數,則+1.code

兩個指針相遇,說明相遇的點的左面全是偶數,相遇點的右面全是奇數,完成。blog

先放代碼,以下:leetcode

class Solution {
    public int[] sortArrayByParity(int[] A) {
        if( A == null) return A;
        
        int l = 0;
        int r = A.length - 1;
        int temp ;
        while (l < r){
            if(A[l] % 2 == 1 && A[r] % 2 == 0){
                temp = A[l];
                A[l] = A[r];
                A[r] = temp;
                l++;
                r--;
            }
            
            if(A[l] % 2 == 0){
                l++;
            }
            
            if(A[r] % 2 == 1){
                r--;
            }
        }
        return A;
    }
}

 

原理圖以下:it

 

收工!io

相關文章
相關標籤/搜索