905. Sort Array By Parity

Description

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 1

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、 题目要求将偶数排在奇数前面, 凡是返回的数组满足这个条件就行;
2、创建一个evenIndex用来标记当前最后一个偶数的下一个位置,遍历整个数组,当遇到偶数的时候,就和该位置的数交换,遍历完所有偶数就交换到了前面;
3、使用位运算判断奇数偶数,奇数的最低位是1,偶数的最低位是0,A[i] & 1这个操作就保留了A[i]的最低位,判断即可。

class Solution {
    public int[] sortArrayByParity(int[] A) {
        if(A.length == 0 || A.length == 1) {
            return A;
        }
        int evenIndex = 0;
        for(int i = 0; i < A.length; i++) {
            if((A[i] & 1) == 0) {
                int temp = A[i];
                A[i] = A[evenIndex];
                A[evenIndex] = temp;
                evenIndex++;
            }
        }
        return A;
        
    }
}
原文地址:https://www.cnblogs.com/zhuobo/p/10605579.html