【Python】【难度:简单】Leetcode 922. 按奇偶排序数组 II

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。

对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。

你可以返回任何满足上述条件的数组作为答案。

示例:

输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
 

提示:

2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-array-by-parity-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution(object):
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        res1=[]
        res2=[]
        res=[]
        for i in A:
            if i%2:
                res1.append(i)
            else:
                res2.append(i)
        for i in range(len(res1)):
            res.append(res2[i])
            res.append(res1[i])
        return res

执行结果:

通过

显示详情

执行用时 :192 ms, 在所有 Python 提交中击败了96.97%的用户

内存消耗 :14.7 MB, 在所有 Python 提交中击败了25.00%的用户

原创文章 105 获赞 0 访问量 1659

猜你喜欢

转载自blog.csdn.net/thomashhs12/article/details/106071276