法一:对数组进行排序,将所有的偶数放到奇数的前面,我们可以考虑使用两个for循环,先将所有的偶数存到数组中,在将所有的奇数存进去
class Solution {
public int[] sortArrayByParity(int[] A) {
int[] B = new int[A.length];
int t = 0;
for(int i = 0;i<A.length;i++){
if(A[i]%2 == 0)
B[t++] = A[i];
}
for(int i = 0;i<A.length;i++){
if(A[i]%2 != 0)
B[t++] = A[i];
}
return B;
}
}
法二:通过比较器对数组进行排序
class Solution {
public int[] sortArrayByParity(int[] A) {
Integer[] B = new Integer[A.length];
for (int t = 0; t < A.length; ++t)
B[t] = A[t];
Arrays.sort(B, (a, b) -> Integer.compare(a%2, b%2));
for (int t = 0; t < A.length; ++t)
A[t] = B[t];
return A;
/* Alternative:
return Arrays.stream(A)
.boxed()
.sorted((a, b) -> Integer.compare(a%2, b%2))
.mapToInt(i -> i)
.toArray();
*/
}
}