剑指offer面试题【21】Leetcode【905】---Sort Array By Parity奇偶排序【Array】【Sort】【Easy】【C++】【Python】

题目描述

给一个非负整数数组A,返回一个数组,该数组由A的所有偶数元素和A的所有奇数元素组成。偶数排在前面,奇数排在后面。偶数和奇数内部可以不排序。

示例

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

思路

遍历数组,判断奇偶数,然后找一个新的数组去存储。

C++代码

class Solution {
public:
    vector sortArrayByParity(vector& A) {
        int len = A.size();
        vector B(len);
        int x=0,y=len-1;
        for(int i=0;i

Python代码

def reOrderArray(array):
        # write code here
        bengin=0
        end=len(array)-1
        while bengin

下面的代码能保证奇偶数的相对位置一致

class Solution:
    def reOrderArray(self, array):
        # write code here
        odd, even = [], []
        for item in array:
            if item%2 == 1:
                odd.append(item)
            else:
                even.append(item)
        return odd+even

 

你可能感兴趣的:(C++,leetcode,剑指offer)