Skip to content

Commit afd4201

Browse files
committed
922
1 parent 25dae52 commit afd4201

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

code/922.sort-array-by-parity-ii.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#
2+
# @lc app=leetcode id=922 lang=python3
3+
#
4+
# [922] Sort Array By Parity II
5+
#
6+
7+
# @lc code=start
8+
class Solution:
9+
def sortArrayByParityII(self, a: List[int]) -> List[int]:
10+
i = 0 # pointer for even misplaced
11+
j = 1 # pointer for odd misplaced
12+
sz = len(a)
13+
14+
# invariant: for every misplaced odd there is misplaced even
15+
# since there is just enough space for odds and evens
16+
17+
while i < sz and j < sz:
18+
if a[i] % 2 == 0:
19+
i += 2
20+
elif a[j] % 2 == 1:
21+
j += 2
22+
else:
23+
# a[i] % 2 == 1 AND a[j] % 2 == 0
24+
a[i],a[j] = a[j],a[i]
25+
i += 2
26+
j += 2
27+
28+
return a
29+
# @lc code=end
30+

0 commit comments

Comments
 (0)