leetcode-922 | 按奇偶排序数组 II

922. 按奇偶排序数组 II

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

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

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

示例 1:
输入:[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

思考

转化一下就是奇数位置放置奇数,偶数位置放置偶数的列表。

class Solution(object):
    def sortArrayByParityII(self, A):
        """
        :type A: List[int]
        :rtype: List[int]
        """
        ou = [i for i in A if i % 2 == 0]
        ji = [i for i in A if i % 2 != 0]
        resu = []
        i = 0
        oui = jii = 0
        while i < len(A):
            if i % 2 == 0:
                if oui < len(ou):
                    resu.append(ou[oui])
                    oui += 1
            else:
                if jii < len(ji):
                    resu.append(ji[jii])
                    jii+=1
            i += 1
        return resu

结果:

执行用时 : 252 ms, 在Sort Array By Parity II的Python提交中击败了69.54% 的用户
内存消耗 : 13.6 MB, 在Sort Array By Parity II的Python提交中击败了37.28% 的用户

提交时间状态执行用时内存消耗语言
几秒前通过252 ms13.6MBpython
## 优化

   Reprint policy


《leetcode-922 | 按奇偶排序数组 II》 by 梦否 is licensed under a Creative Commons Attribution 4.0 International License
 Previous
scrapy-1 |  安装scrapy scrapy-1 | 安装scrapy
决定系统化的学习爬虫,使用Python实现。以下内容来自博客园、CSDN等。非原创。 1、安装wheel(安装后,便支持通过wheel文件安装软件)pip3 install wheel 2、安装lxml、pyopenssllxml:解析XM
2019-06-04
Next 
leetcode-999 |  车的可用捕获量 leetcode-999 | 车的可用捕获量
999. 车的可用捕获量在一个 8 x 8 的棋盘上,有一个白色车(rook)。也可能有空方块,白色的象(bishop)和黑色的卒(pawn)。它们分别以字符 “R”,“.”,“B” 和 “p” 给出。大写字符表示白棋,小写字符表示黑棋。
2019-06-03
  TOC