[leetcode-905-Sort Array By Parity]

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. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

思路:

扫描两遍数组,第一遍统计偶数的个数,然后第二趟把偶数放到对应位置。

vector<int> sortArrayByParity(vector<int>& A)
{
    int n = A.size();
    int evenNum = 0;   
    for(int i = 0; i < n; i++)
    {
        if(A[i] % 2 == 0)evenNum++;
    }    
    vector<int> ret(n);
    int evenIndex =0;
    int oddIndex = evenNum;
    for(int i = 0; i < n; i++)
    {
        if(A[i] % 2 == 0)ret[evenIndex++] = A[i];
        else ret[oddIndex++] = A[i];
    }
    return ret;
}

见到了一个更快速的版本,不需要申请内存空间,直接操作原数组的方法。

vector<int> sortArrayByParity(vector<int>& A) {
        int i=0;
        for(int k=0;k<A.size();k++){
            if(A[k]%2==0){
                swap(A[i],A[k]);
                i++;
            }
        }
        return A;
    }

猜你喜欢

转载自www.cnblogs.com/hellowooorld/p/9750528.html
今日推荐