跳转至

905.Sort Array By Parity

Tags:Easy Array

Link: https://leetcode.com/problems/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

Answer:

class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& A) {
        int index = 0;

        for(int i = 0; i < A.size(); ++i){
            if(A[i] % 2 == 0){
                swap(A[i], A[index]);
                ++index;
            }
        }

        return A;
    }
};

解析:

思路和删除数组中相同元素类似,用一个index来记录临界点,并不需要考虑特殊情形,因为无论如何分类讨论,最终都需要遍历整个数组。