Skip to content

Commit b2db73f

Browse files
authored
Create sort-array-by-parity.py
1 parent 7fa5579 commit b2db73f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Python/sort-array-by-parity.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Given an array A of non-negative integers,
5+
# return an array consisting of all the even elements of A,
6+
# followed by all the odd elements of A.
7+
#
8+
# You may return any answer array that satisfies this condition.
9+
#
10+
# Example 1:
11+
#
12+
# Input: [3,1,2,4]
13+
# Output: [2,4,3,1]
14+
# The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3]
15+
# would also be accepted.
16+
#
17+
# Note:
18+
# - 1 <= A.length <= 5000
19+
# - 0 <= A[i] <= 5000
20+
21+
class Solution(object):
22+
def sortArrayByParity(self, A):
23+
"""
24+
:type A: List[int]
25+
:rtype: List[int]
26+
"""
27+
i = 0
28+
for j in xrange(len(A)):
29+
if A[j] % 2 == 0:
30+
A[i], A[j] = A[j], A[i]
31+
i += 1
32+
return A

0 commit comments

Comments
 (0)