一、题目描述
- 给定一个非负整数数组 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] <= 50001
三、思路
先将偶数放进一个集合,后再将奇数放入剩下的集合。
四、代码实现
1.我的实现
public class Solution905 {
public static int[] sortArrayByParity(int[] a) {
if (a.length == 0){
return null;
}
int[] b = new int[a.length];
int bIndex = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0){
b[bIndex] = a[i];
a[i] = -1;
bIndex++;
}
}
for (int i = 0; i < a.length; i++) {
if (a[i] == -1){
continue;
}
b[bIndex] = a[i];
bIndex ++;
}
return b;
}
public static int[] sortArrayByParity1(int[] a) {
if (a.length == 0){
return null;
}
int[] b = new int[a.length];
int bStartIndex = 0;
int bEndIndex = b.length - 1;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0){
b[bStartIndex] = a[i];
bStartIndex++;
}else{
b[bEndIndex] = a[i];
bEndIndex --;
}
}
return b;
}
public static void main(String[] args) {
int[] a = new int[5000];
for (int i = 0; i < 5000; i++) {
a[i] = i +1;
}
long begin = System.currentTimeMillis();
System.out.println(Arrays.toString(sortArrayByParity1(new int[]{23,32,12,74,45,77,34,42})));
System.out.println(Arrays.toString(sortArrayByParity1(a)));
long end = System.currentTimeMillis();
System.out.println(begin);
System.out.println(end);
System.out.println("执行时间:" + (end - begin) + "ms");
}
}
2.leetCode效率最高的代码
public int[] sortArrayByParity2(int[] A) {
int i = 0;
int j = A.length-1;
while(i<j) {
if(A[i]%2 > A[j]%2){
int tmp = A[j];
A[j] = A[i];
A[i] = tmp;
}
if(A[i]%2==0) {
i++;
}
if(A[j]%2!=0){
j--;
}
}
return A;
}
五、总结
- 结论:leetCode执行时间:13-24ms;97%。
- 总结:leetCode上效率最高的代码,执行速度10ms。速度快的原因大概是因为空间复杂度是O(1)级别的。这个问题的关键是利用好index。通过看别人的代码,发现了一个遗漏的基础知识点。
- 笔记:使用& 运算符可以判断奇偶数。如:8 & 1 = 0; 7 & 1 = 1。
感谢阅读。