Skip to content

Commit fe37052

Browse files
committed
922
1 parent b1ea733 commit fe37052

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

TP/922.md

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
## 922 Sort Array By Parity II
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/sort-array-by-parity-ii/discuss/?currentPage=1&orderBy=most_votes&query=)
6+
7+
---
8+
9+
#### Solution
10+
11+
- See Code
12+
13+
---
14+
15+
#### Code
16+
17+
O(n)
18+
O(1)
19+
20+
```python
21+
class Solution:
22+
def sortArrayByParityII(self, a: List[int]) -> List[int]:
23+
i = 0 # pointer for even misplaced
24+
j = 1 # pointer for odd misplaced
25+
sz = len(a)
26+
27+
# invariant: for every misplaced odd there is misplaced even
28+
# since there is just enough space for odds and evens
29+
30+
while i < sz and j < sz:
31+
if a[i] % 2 == 0:
32+
i += 2
33+
elif a[j] % 2 == 1:
34+
j += 2
35+
else:
36+
# a[i] % 2 == 1 AND a[j] % 2 == 0
37+
a[i],a[j] = a[j],a[i]
38+
i += 2
39+
j += 2
40+
41+
return a
42+
```

0 commit comments

Comments
 (0)