您的位置 首页 > 腾讯云社区

LeetCode 905. 按奇偶排序数组---村雨遥

题目905. 按奇偶排序数组[1]描述给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。 你可以返回满足此条件的任何数组作为答案。 示例: 输入:[3,1,2,4] 输出:[2,4,3,1] 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。 解题思路遍历数组,先将偶数存入数组;再次遍历数组,将奇数存入数组;返回结果数组resultArr;实现package Array; /** * Created with IntelliJ IDEA. * Version : 1.0 * Author : cunyu * Email : cunyu1024@foxmail.com * Website : https://cunyu1943.github.io * Date : 2020/4/3 16:22 * Project : LeetCode * Package : Array * Class : NineZeroFive * Desc : 905. 按奇偶排序数组 */ public class NineZeroFive { public static void main(String[] args) throws Exception { NineZeroFive nineZeroFive = new NineZeroFive(); int[] A = {3, 1, 2, 4}; for (int item : nineZeroFive.sortArrayByParity(A) ) { System.out.print(item + "t"); } } public int[] sortArrayByParity(int[] A) { int size = A.length; int index = 0; int[] resultArr = new int[size]; for (int item : A ) { if (item % 2 == 0) { resultArr[index++] = item; } } for (int item : A ) { if (item % 2 != 0) { resultArr[index++] = item; } } return resultArr; } } 参考资料

[1]

905. 按奇偶排序数组: https://leetcode-cn.com/problems/sort-array-by-parity/

---来自腾讯云社区的---村雨遥

关于作者: 瞎采新闻

这里可以显示个人介绍!这里可以显示个人介绍!

热门文章

留言与评论(共有 0 条评论)
   
验证码: