头像

带翅膀的猫

时光荏苒,我们一直都在

《LeetCode刷题(Easy Rank):905. Sort Array By Parity》

 1月前  •   LeetCode  •     •   6  •   0

Question:

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.You may return any answer array that satisfies this condition.

Example:

示例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.

Solution:

JAVAclass Solution {
    public int[] sortArrayByParity(int[] A) {
        int s = 0, e = A.length - 1;
        while(s < e){
            while((A[s] & 1) == 0 && s < e) s++;//s指向奇数
            while((A[e] & 1) == 1 && s < e) e--;//e指向偶数
            int tmp = A[s];//奇偶交换
            A[s++] = A[e];
            A[e--] = tmp;
        }
        return A;
    }
}

 

上一篇:
下一篇:

 评论


 已有0条评论

    还没有任何评论,你来说两句吧!