日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

LeetCode 922 Sort Array By Parity II 解题报告

發布時間:2025/5/22 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。