905. Sort Array By Parity

Posted zhuobo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
        
    }
}

以上是关于905. Sort Array By Parity的主要内容,如果未能解决你的问题,请参考以下文章

905. Sort Array By Parity

leetcode905. Sort Array By Parity

Leetcode905 Sort Array By Parity

[LeetCode&Python] Problem 905: Sort Array By Parity

Leetcode 905. Sort Array By Parity

[leetcode][easy][Array][905][Sort Array By Parity]