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
? ? ? ? ? ??
? ? ? ??
?
轉載于:https://www.cnblogs.com/yao1996/p/10357160.html
總結
以上是生活随笔為你收集整理的LeetCode 922 Sort Array By Parity II 解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 验证码画布生成以及点击图片切换验证码
- 下一篇: [Swift通天遁地]九、拔剑吧-(9)