LeetCode 905. Sort Array By Parity (C++ C JAVA Python3 实现)

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

题目非常简单,就是把一个数组里面的偶数放到前面奇数放到后面,常规的思路就是新建一个同样大小辅助数组,然后遍历原数组,将偶数放入数组头部,奇数放入数组尾部。

C++实现:

int x=[](){
   std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& A) {
         int n = A.size();
        vector <int> temp(n);
        int p = 0;
        int q = n - 1;
        for(int i = 0 ;i < n ;i++)
        {
            if(A[i] % 2 == 0 ){
                temp[p++] = A[i];
            }else{
                temp[q--] = A[i];
            }
        }
        return temp;
    }
};

C实现:

并不怎么会C语言,面对这个函数头部,感觉到一些疑惑,A是待排数组,ASize是待排数组大小,returnSize是结果数组还是结果数组的大小。瞎写了一下发现returnSize是一个指针,指向存储结果数组的大小的指针变量。(可是结果数组的大小和原数组大小不是一致吗???)

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* sortArrayByParity(int* A, int ASize, int* returnSize) {
        *returnSize = ASize;
        int* temp = (int*)malloc(ASize*sizeof(int));
        int k = 0;
        int n = ASize;
        int j = n - 1;
        for(int i = 0; i < n; i++)
        {
            if(A[i]%2 == 0)
            {
                temp[k++]=A[i];
            }else{
                temp[j--]=A[i];
            }
        }
    return temp;
}

JAVA实现:

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int n = A.length;
        int []arr = new int[n];
        int p = 0 , q = n - 1;
        for(int i = 0; i < n; i++){
            if(A[i] % 2 == 0)
                arr[p++] = A[i];
            else
                arr[q--] = A[i];
        }
        return arr;
    }
}

Python3实现:

超精简版:

class Solution:
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        return sorted(A, key = lambda x : x % 2)

具体理解可以参见博客python3 sorted()的用法

对C++熟悉的我更喜欢下列

class Solution:
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        even , odd = [] ,[]
        for i in A:
            if i % 2 == 0:
                even.append(i)
            else:
                odd.append(i)
        return even + odd

或是这种

class Solution:
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        o = [each for each in A if each % 2 == 0]
        j = [each for each in A if not each % 2 == 0]
        return o + j
        

猜你喜欢

转载自blog.csdn.net/qq_25406563/article/details/83046988