版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39360985/article/details/84403808
给定一个非负整数数组 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
题目分析:
一、使用额外空间
新定义一个数组,然后在给定的数组中遍历奇偶数,将最后的数据存入新数组中
代码实现:
public int[] sortArrayByParity(int[] A) { int[] temp = new int[A.length]; int begin = 0; int end = A.length - 1; for (int i = 0; i < A.length; i++) { if (A[i] % 2 == 0){ temp[begin] = A[i]; begin++; } else{ temp[end] = A[i]; end--; } } return temp; }
二、不使用额外空间
设置双指针,从数组的首位和末尾遍历,符合条件(偶数要排在前面,奇数要排在后面)就交换
代码实现:
public int[] sortArrayByParity(int[] A) { int i = 0; int j = A.length - 1; while (i < j){ if (A[i] % 2 == 1 && A[j] % 2 == 0) { int temp = A[j]; A[j] = A[i]; A[i] = temp; } if (A[i] % 2 == 0){ i++; } if (A[j] % 2 == 1){ j--; } } return A; }
主函数:
public static void main(String[] args) { A1 a = new A1(); int[] test = {3,1,2,4,1}; int[] res = a.sortArrayByParity(test); for (int i = 0; i < res.length; i++) { System.out.print(res[i] + " "); } }
运行结果:
4 2 1 3 1