给定一个非负整数数组 A
,返回一个数组,在该数组中, A
的所有偶数元素之后跟着所有奇数元素。
输入:[3,1,2,4]
输出:[2,4,3,1]
输出 [4,2,3,1]或[2,4,1,3] 或[4,2,1,3]
import java.util.Arrays;
import java.util.Scanner;
class Solution {
public int[] sortArrayByParity(int[] A) {
int[] result=new int[A.length];
int left=0;
for (int i = 0; i <A.length ; i++) {
if(A[i]%2==0){
result[left]=A[i];
left++;
}
}
for (int i = 0; i <A.length ; i++) {
if(A[i]%2!=0){
result[left]=A[i];
left++;
}
}
return result;
}
}
class Solution {
// public int[] sortArrayByParity(int[] A) {
// int[] ans = new int[A.length];
// int left = 0,right = A.length - 1;
// for (int i = 0; i < A.length; i++) {
// if(A[i]%2 == 0){
// ans[left] = A[i];
// left++;
// }else{
// ans[right] = A[i];
// right--;
// }
// }
// return ans;
// }
//}
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] arr = new int[num];
for (int i = 0; i < num; i++) {
arr[i] = sc.nextInt();
}
Solution Solution = new Solution();
//变为数组打印出来
//System.out.println(Arrays.toString(Solution.sortArrayByParity(arr)));
pr(Solution.sortArrayByParity(arr));
}
public static void pr(int[] ar){
for (int i = 0; i < ar.length; i++) {
System.out.print(ar[i]+" ");
}
}