LeetCode 905 Sort Array By Parity 解題報告
阿新 • • 發佈:2019-01-05
題目要求
Given an array A
of non-negative integers, return an array consisting of all the even elements of A
, followed by all the odd elements of A
.
You may return any answer array that satisfies this condition.
題目分析及思路
題目給出一個含有非負整數的陣列A,要求返回一個數組,前面的元素都是A中的偶數,後面的元素都是A中的奇數。可以新建一個list,先遍歷A
A
一次,這次只插入奇數元素。
python程式碼
class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
res = list()
for e in A:
if e % 2 == 0:
res.append(e)
for e in A:
if e % 2 == 1:
res.append(e)
return res