We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 25dae52 commit afd4201Copy full SHA for afd4201
code/922.sort-array-by-parity-ii.py
@@ -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
26
27
28
+ return a
29
+# @lc code=end
30
0 commit comments