[LeetCode]#905. Sort Array By Parity

Fatboy Slim
1 min readMay 1, 2020

--

Environment: Python 3.7

Key technique: append

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.

Analysis:

  1. If A[i]/2 remainder is even, add it to even list
  2. Else, add it to odd list.
  3. Combine even and odd list.

Solution:

class Solution:
def sortArrayByParity(self, A):
odd, even=[],[]
l=len(A)
for i in range(l):
if A[i] % 2 ==0:
even.append(A[i])
else:
odd.append(A[i])
return even+odd

Submissions:

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet