Given an array A of non-negative(非负整数) integers, return an array consisting of all the even(奇数) elements of A, followed by all the odd(偶数) elements of A.
You may return any answer array that satisfies this condition.
把偶数放前面,把奇数放后面
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
第一种做法:两个循环,第一个循环把偶数找出来放到一个新数组,第二个循环把奇数找出来放到新数组里
class Solution {
public int[] sortArrayByParity(int[] A) {
int []result=new int[A.length];
int k=0;
for(int i=0;i<A.length;i++){
if(A[i]%2==0){
result[k++]=A[i];
}
}
for(int i=0;i<A.length;i++){
if(A[i]%2!=0){
result[k++]=A[i];
}
}
return result;
}
}
第2中做法:
class Solution {
public int[] sortArrayByParity(int[] A) {
int i=0;
int j=A.length-1;
while(i<j){
//A[i]%2==0为偶数,A[i]%2==1为奇数
//从头开始的数 跟 末尾的数比较是奇数就放到后面去,是偶数就放前面来
if(A[i]%2 >A[j]%2){
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
//如果从头方向开始比较的数已经是偶数了,往下一个数来继续判断是奇数还是偶数
if(A[i]%2==0) i++;
//如果最后一个数已经是奇数了,往前移动一位来判断
if(A[j]%2==1) j--;
}
return A;
}
}