https://leetcode-cn.com/problems/sort-array-by-parity/description/
*
* algorithms
* Easy (69.43%)
* Total Accepted: 12.3K
* Total Submissions: 17.7K
* Testcase Example: '[3,1,2,4]'
*
* 给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素。
*
* 你可以返回满足此条件的任何数组作为答案。
*
*
*
* 示例:
*
* 输入:[3,1,2,4]
* 输出:[2,4,3,1]
* 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。
*
*
*
*
* 提示:
*
*
* 1 <= A.length <= 5000
* 0 <= A[i] <= 5000
*
*
*/
class Solution {
public int[] sortArrayByParity(int[] A) {
//遍历数组中的元素
int i=0;
int j=A.length-1;
while (i<=j) {
int numleft= A[i];
int numright = A[j];
//交换两个数
if (!isO(numleft) && isO(numright)) {
swap(i,j,A);
}
if (isO(numleft)) {
i++;
}
if (!isO(numright)) {
j--;
}
}
return A;
}
private static void swap(int i, int j, int[] a) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
//判断元素是不是偶数或者奇数
public static boolean isO(int number){
if (number % 2 == 0) {
return true;
}
return false;
}
}