关注 每天一道编程题 专栏,一起学习进步。

题目

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.

Note:

1 <= A.length <= 5000
0 <= A[i] <= 5000

分析

题意:给一个正整数数组,把所有偶数放前面,奇数放后面

算法:
新建一个等大的空数组,如果是偶数,就从前往后放进去,如果是奇数,就从后往前放进去。

解答

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int size=A.length;
        int[] B = new int[size];
        int start=0;
        int end=size-1;
        for(int i=0;i<A.length;i++){
            if(A[i]%2==0){
                B[start++]=A[i];
            }else{
                B[end--]=A[i];
            }
        }
        return B;
    }
}

优化

当我想到第一个算法的时候,就想到能否在内部直接实现交换,不需要额外创建一个数组,考虑了下,应该是可行的。

弄一个头指针指向数组开头,尾指针指向数组结尾,从头开始遍历,但只遍历数组的一半
如果头指针指向的数是偶数,则头指针++
否则
	如果尾指针指向的数是奇数,则尾指针--
	否则
		将头尾数交换,start++,end--
class Solution {
    public int[] sortArrayByParity(int[] A) {
        int start=0;
        int end=A.length-1;
        while(start<end){
            if(A[start]%2==0){
                start++;
            }else if(A[end]%2!=0){
                end--;
            }else{
                int tmp=A[start];
                A[start]=A[end];
                A[end]=tmp;
                start++;
                end--;
            }
        }
        return A;
    }
}

然而,不知道为什么,这种方式空间开销更大,明明少了一个中间数组,而且减少了循环次数。

评论区解答,逻辑更加简单。
如果当前数是偶数,那就放到“当前所有偶数的最后面”,并让这个界限i++;

 public int[] sortArrayByParity(int[] A) {
        for (int i = 0, j = 0; j < A.length; j++)
            if (A[j] % 2 == 0) {
                int tmp = A[i];
                A[i++] = A[j];
                A[j] = tmp;;
            }
        return A;
    }