forked from qiyuangong/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path905_Sort_Array_By_Parity.java
More file actions
36 lines (34 loc) · 960 Bytes
/
905_Sort_Array_By_Parity.java
File metadata and controls
36 lines (34 loc) · 960 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
/* public int[] sortArrayByParity(int[] A) {
A = Arrays.stream(A).
boxed().
sorted((a, b) -> Integer.compare(a% 2, b % 2)).
mapToInt(i -> i).
toArray();
return A;
}*/
/*public int[] sortArrayByParity(int[] A) {
int[] ans = new int[A.length];
int pos = 0;
for (int num: A)
if (num % 2 == 0)
ans[pos++] = num;
for (int num: A)
if (num % 2 == 1)
ans[pos++] = num;
return ans;
}*/
public int[] sortArrayByParity(int[] A) {
int lo = 0, hi = A.length - 1;
while (lo < hi) {
if (A[lo] % 2 > A[hi] % 2) {
int tmp = A[hi];
A[hi] = A[lo];
A[lo] = tmp;
}
if (A[lo] % 2 == 0) lo++;
if (A[hi] % 2 == 1) hi--;
}
return A;
}
}