题解 | #移动数组中元素的位置#
调整数组顺序使奇数位于偶数前面(一)
http://www.nowcoder.com/practice/ef1f53ef31ca408cada5093c8780f44b
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] reOrderArray (int[] array) {
//解法一:时间复杂度O(n),空间复杂度O(n)
int[] temp = new int[array.length] ;
int oIndex = 0 ;//奇数索引
int oCount = 0 ;//奇数的数量
//统计奇数的数量
for(int i = 0 ; i < array.length ; i ++) {
if(array[i] % 2 != 0) {
oCount++ ;
}
}
int eIndex = oCount ;//偶数索引
//将原数组的值 赋给 新数组
for(int i = 0 ; i < array.length ; i ++) {
int num = array[i] ;
if(num % 2 == 0) {
temp[eIndex++] = num ;
} else {
temp[oIndex++] = num ;
}
}
return temp ;
}
}
一个菜鸟的算法刷题记录 文章被收录于专栏
分享一个菜鸟的成长记录
查看12道真题和解析