首页 > 其他 > 详细

LeetCode 922 Sort Array By Parity II 解题报告

时间:2019-02-09 10:31:48      阅读:547      评论:0      收藏:0      [点我收藏+]

题目要求

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

You may return any answer array that satisfies this condition.

题目分析及思路

题目给出一个整数数组A,其中一半是奇数,一半是偶数,要求重新排序数组,索引为奇数的是奇数,索引为偶数的是偶数。可以分别获取奇数列表和偶数列表,然后遍历索引,依次取值。

python代码

class Solution:

    def sortArrayByParityII(self, A: ‘List[int]‘) -> ‘List[int]‘:

        odd = [i for i in A if i % 2 == 1]

        even = [i for i in A if i % 2 == 0]

        res = []

        for i in range(len(A)):

            if i % 2 == 1:

                res.append(odd.pop())

            else:

                res.append(even.pop())

        return res

            

        

 

LeetCode 922 Sort Array By Parity II 解题报告

原文:https://www.cnblogs.com/yao1996/p/10357160.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!