题目:
给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素。
你可以返回满足此条件的任何数组作为答案。
示例:
代码:
- 解法一
//使用夹逼思想
class Solution {
public int[] sortArrayByParity(int[] A) {
if(A==null||A.length==0){
return null;
}
int start=0;
int end=A.length-1;
while(start<end){
if(A[start]%2==0&&A[end]%2==0){
start++;
}else if(A[start]%2==0&&A[end]%2==1){
start++;
end--;
}else if(A[start]%2==1&&A[end]%2==0){
int temp=A[start];
A[start]=A[end];
A[end]=temp;
}else{
end--;
}
}
return A;
}
}
- 解法二
//使用插入排序
class Solution {
public int[] sortArrayByParity(int[] A) {
if(A==null||A.length==0){
return null;
}
for(int i=1;i<A.length;i++){
if(A[i]%2==0){
int temp=A[i];
int j=i;
for(;j>0&&A[i-1]%2==1;j--){
A[j]=A[j-1];
}
A[j]=temp;
}
}
return A;
}
}
- 别人的代码
class Solution {
public int[] sortArrayByParity(int[] A) {
if(A==null||A.length==1){
return A;
}
//归并排序
int left=0;//向右走
int right=A.length-1;//向左走
while(left<right){
while(left<right&&A[left]%2==0){//找到奇数坐标就跳出循环
++left;
}
while(left<right&&A[right]%2==1){//找到偶数坐标就跳出循环
--right;
}
//交换后
swap(A,left,right);
}
return A;
}
public void swap(int[] A, int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}