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.

题目分析及思路

题目给出一个含有非负整数的数组A,要求返回一个数组,前面的元素都是A中的偶数,后面的元素都是A中的奇数。可以新建一个list,先遍历A一次,把偶数元素都插入到里面;再遍历A一次,这次只插入奇数元素。

python代码​

class Solution:

    def sortArrayByParity(self, A):

        """

        :type A: List[int]

        :rtype: List[int]

        """

        res = list()

        for e in A:

            if e % 2 == 0:

                res.append(e)

        for e in A:

            if e % 2 == 1:

                res.append(e)

        return res

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10223383.html
今日推荐