LeetCode 922 Sort Array By Parity II 解题报告
Posted yao1996
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于LeetCode 922 Sort Array By Parity II 解题报告的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 922 Sort Array By Parity II 解题报告
LeetCode 922. Sort Array By Parity II (按奇偶排序数组 II)
Leetcode 922. Sort Array By Parity II