import java.util.Arrays;
/**
-
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,
-
使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,
-
并保证奇数和奇数,偶数和偶数之间的相对位置不变。
-
思路:
-
新开辟一个数组,用两个for循环就成
*/
public class Practice13 {public static void main(String[] args) {
Practice13 p = new Practice13();
int[] array = new int[]{1, 2, 3, 4, 5, 6, 7};
p.reOrderArray(array);
}public void reOrderArray(int[] array) {
int[] preArray = new int[array.length];
int count = 0;
//判断数组是否为空
if (array.length == 0) {
System.out.println(“数组为空!”);
return;
}
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) {
preArray[count] = array[i];
count++;
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
preArray[count] = array[i];
count++;
}
}
System.arraycopy(preArray,0,array,0, preArray.length);
System.out.println(Arrays.toString(array));
}
}
emmm,剑指offer的题目是比力扣的简单很多,都还蛮基础哈哈哈,所以给了我这种菜鸟一丝喘息的机会,大家加油!
原文链接:https://www.nowcoder.com/practice/beb5aa231adc45b2a5dcc5b62c93f593?tpId=13&tqId=11166&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking