-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathlc922.java
38 lines (37 loc) · 1.11 KB
/
lc922.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
package code;
/*
* 922. Sort Array By Parity II
* 题意:奇数位置上都是奇数,偶数位置上都是偶数
* 难度:Easy
* 分类:Array, Sort
* 思路:题看似简单,但最优的方法并不好写
* Tips:
*/
public class lc922 {
public int[] sortArrayByParityII(int[] A) { //O(N^2)
for (int i = 0; i < A.length ; i++) {
if( A[i]%2==i%2 ) continue;
for (int j = i+1; j < A.length ; j++) {
if(A[i]%2!=A[j]%2) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
break;
}
}
}
return A;
}
public int[] sortArrayByParityII2(int[] A) { //很巧妙的方法 O(N)时间, O(1)空间
int cur = 1; //奇数位置的位置
for (int i = 0; i < A.length ; i+=2) { //这里+2 只判断偶数位置上是否符合
if(A[i]%2==1){
while(A[cur]%2==1) cur+=2;
int temp = A[cur];
A[cur] = A[i];
A[i] = temp;
}
}
return A;
}
}