标签:整数 The leetcode python cond sel 排序数组 yii condition
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,其中一半是奇数,一半是偶数,要求重新排序数组,索引为奇数的是奇数,索引为偶数的是偶数。可以分别获取奇数列表和偶数列表,然后遍历索引,依次取值。
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 解题报告
标签:整数 The leetcode python cond sel 排序数组 yii condition
原文地址:https://www.cnblogs.com/yao1996/p/10357160.html