-
Notifications
You must be signed in to change notification settings - Fork 8
/
SortArrayByParityII.java
64 lines (59 loc) · 1.76 KB
/
SortArrayByParityII.java
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package array;
// Source : https://leetcode.com/problems/sort-array-by-parity-ii/
// Id : 922
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2019-04-15
// Topic : Array
// Level : Easy
// Result : 99.72% 99.43%
class SortArrayByParityII {
//60.45% 3 ms 99.32% 40.4 MB
public int[] sortArrayByParityIIOrigin(int[] A) {
int i = 0;
int j = 1;
// below code hasn't take full advantage of half odd half even situation
// if do count before swap which can be improved under above condition
// see improved code in the next function
while (true) {
if (i >= A.length || j >= A.length) {
return A;
}
if (A[i] % 2 == 1 && A[j] % 2 == 0) {
swapNumInArray(i, j, A);
}
if (A[i] % 2 == 0) {
i += 2;
//in order to make sure a count is performed
continue;
}
if (A[j] % 2 == 1) {
j += 2;
//in order to make sure a count is performed
continue;
}
}
}
public void swapNumInArray(int firstIndex, int secondIndex, int[] array) {
int tmp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = tmp;
}
// 99.72% 99.43%
public int[] sortArrayByParityII(int[] A) {
int i = 0;
int j = 1;
int tmp;
while (i < A.length) {
if ((A[i] & 0x1) == 1) {
while ((A[j] & 0x1) == 1) {
j += 2;
}
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
i += 2;
}
return A;
}
}