LeetCode 922 Sort Array By Parity II 解题报告

题目要求

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

            

        

 

上一篇:STL的function object concepts


下一篇:LeetCode 985 Sum of Even Numbers After Queries 解题报告