1. 程式人生 > >[leetcode]905. Sort Array By Parity

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

################################################ 我的答案:

class Solution:
    def sortArrayByParity(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        list_even = [ a for a in A if (a%2 == 0) ]
        list_odd = [a for a in A if (a%2 == 1) ]
        return list_even + list_odd

總覺得有點笨,遍歷了兩次列表. 果然, Complexity Analysis Time Complexity: O(N), where NN is the length of A. Space Complexity: O(N), the space used by the answer.

另外還有兩種方法: 方法1: 排序

class Solution(object):
    def sortArrayByParity(self, A):
        A.sort(key = lambda x: x % 2)
        return A

當元素為偶數時, key的返回值為0,所以排在前面,奇數時,key返回值為1,所以排在後面.

list的sort: 語法 sort()語法: list.sort(cmp=None, key=None, reverse=False) 引數 cmp – 可選引數, 如果指定了該引數會使用該引數的方法進行排序。 key – 主要是用來進行比較的元素,只有一個引數,具體的函式的引數就是取自於可迭代物件中,指定可迭代物件中的一個元素來進行排序。 reverse – 排序規則,reverse = True 降序, reverse = False 升序(預設)。

這個答案的時間複雜度更差了,空間一樣: Time Complexity: O(N \log N), where NN is the length of A. Space Complexity: O(N)for the sort, depending on the built-in implementation of sort.

方法2: 設定兩個遊標, 一個i從前往後遍歷,一個j從後往前遍歷, 如果i遇到奇數, 且j遇到偶數,兩個元素互換.

class Solution(object):
    def sortArrayByParity(self, A):
        i, j = 0, len(A) - 1
        while i < j:
            if A[i] % 2 > A[j] % 2:
                A[i], A[j] = A[j], A[i]

            if A[i] % 2 == 0: i += 1
            if A[j] % 2 == 1: j -= 1

        return A

但我估計平時用python的工作中,如果沒有特別要求,不會花時間搞這個,還是簡單的sort比較常用.

這個方法複雜度: Time Complexity: O(N), where NN is the length of A. Each step of the while loop makes j-i decrease by at least one. (Note that while quicksort is O(N \log N)normally, this is O(N)because we only need one pass to sort the elements.) Space Complexity: O(1) in additional space complexity.