【python3】leetcode 905. Sort Array By Parity(easy)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/84997030

905. Sort Array By Parity(easy)

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.

 listcomp分离出odd和even拼接一下就好啦

简单在没要求inplace

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

Runtime: 88 ms, faster than 53.48% of Python3 

记录一下solution的解法

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

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/84997030
今日推荐