905. Sort Array By Parity
Problem 905
https://leetcode.com/problems/sort-array-by-parity/
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.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Solution
class Solution(object):
def sortArrayByParity(self, A):
Ans = []
for a in A:
if a%2:
Ans.append(a)
else:
Ans.insert(0,a)
return Ans
# solution by two pass
class Solution_two(object):
def sortArrayByParity(self, A):
Ans = [ x for x in A if x % 2 == 0 ] + [ x for x in A if x % 2 == 1 ]
return Ans
# solution by two list
class Solution_list(object):
def sortArrayByParity(self, A):
even, odd = [], []
for a in A:
if a % 2: odd.append(a)
else: even.append(a)
return even + odd
Last updated