-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSortArrayByParity.java
More file actions
33 lines (33 loc) · 865 Bytes
/
SortArrayByParity.java
File metadata and controls
33 lines (33 loc) · 865 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
package io.ziheng.array.leetcode;
/**
* LeetCode 905. Sort Array By Parity
* https://leetcode.com/problems/sort-array-by-parity/
*/
public class SortArrayByParity {
public int[] sortArrayByParity(int[] A) {
if (A == null || A.length == 0) {
return new int[0];
}
int pLeft = 0;
int pRight = A.length - 1;
while (pLeft < pRight) {
while (!isEven(A[pRight]) && pLeft < pRight) {
pRight--;
}
while (isEven(A[pLeft]) && pLeft < pRight) {
pLeft++;
}
swap(A, pLeft, pRight);
}
return A;
}
private void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
private boolean isEven(int num) {
return num % 2 == 0;
}
}
/* EOF */