905. 按奇偶排序数组[1]
给定一个非负整数数组
A
,返回一个数组,在该数组中,A
的所有偶数元素之后跟着所有奇数元素。 你可以返回满足此条件的任何数组作为答案。 示例: 输入: [3,1,2,4] 输出: [2,4,3,1] 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。
result
用来存放最终结果result
中,第二次将奇数存入 result
中.
public int[] sortArrayByParity(int[] A) {
// 存放最终结果
int[] result = new int[A.length];
int index = 0;
// 第一次遍历,将偶数存入 result 数组
for (int item : A) {
if (item % 2 == 0) {
result[index++] = item;
}
}
// 第二次遍历,将奇数存入 result 数组
for (int item : A) {
if (item % 2 != 0) {
result[index++] = item;
}
}
return result;
}
[1]
905. 按奇偶排序数组: https://leetcode-cn.com/problems/sort-array-by-parity/
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有