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;
}
本文介绍了一种简单的Java方法,通过遍历两次将整数数组nums中的偶数和奇数分开,然后分别插入到结果数组res中,以实现按奇偶顺序排序。示例和代码展示了如何使用这种方法来重新组织给定的整数数组。
1192

被折叠的 条评论
为什么被折叠?



