1. 程式人生 > >LeetCode 922 Sort Array By Parity II 解題報告

LeetCode 922 Sort Array By Parity II 解題報告

integer sat con == ans 取值 else and 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,其中一半是奇數,一半是偶數,要求重新排序數組,索引為奇數的是奇數,索引為偶數的是偶數。可以分別獲取奇數列表和偶數列表,然後遍歷索引,依次取值。

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 解題報告