1. 程式人生 > >LeetCode 905. Sort Array By Parity (C++ C JAVA Python3 實現)

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)

對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