package Soution;
class Solution905 {
public int[] sortArrayByParity(int[] A) {
/**
* 解法一:头尾交换
* 在没有参数说明之前, 最好进行判断
* 左偶右奇L++ R--
* 左偶右偶 L++
* 左奇右奇R--
* 左奇右偶 交换
*/
if(A==null||A.length==1||A.length==0) {
return A;
}
//左指针
int L=0;
//右指针
int R=A.length-1;
while(L<R) {
if(A[L]%2==0&&A[R]%2==1) {
L++;
R--;
}else if(A[L]%2==0&&A[R]%2==0) {
L++;
}else if(A[L]%2==1&&A[R]%2==1) {
R--;
}else {
int temp =A[L];
A[L]=A[R];
A[R]=temp;
}
}
return A;
}
}
解法二:
package Soution;
public class Solution905a {
public int[] sortArrayByParity(int[] A) {
/**
* 解法2:不改变原先数字的相对顺序
* 冒泡排序O(n)
* 选择排序O(n)
* 插入排序o(n) 是保证相对顺序的
*/
int e=0;
int j=0;
for(int i =1;i<A.length;i++) {
if(A[i]%2==1) {
continue;
}
e=A[i];
for(j=i;j>0&&A[j-1]%2==1;j--) {
A[j]=A[j-1];
}
A[j]=e;
}
return A;
}
}