[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.

参考:
https://docs.python.org/3/howto/sorting.html
https://leetcode.com/articles/sort-array-by-parity/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值