Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
按奇偶顺序排序,把数组的偶数放在前面,奇数放在后面。
思路:
遍历两次数组,第一次把偶数填进前半段,第二次把奇数填到后半段。
public int[] sortArrayByParity(int[] nums) {
int n = nums.length;
int[] res = new int[n];
int i = 0;
for(int num : nums) {
if(num % 2 == 0) {
res[i] = num;
i ++;
}
}
for(int num : nums) {
if(num % 2 != 0) {
res[i] = num;
i ++;
}
}
return res;
}