剑指Offer_调整整数数组使奇数位于偶数前面
题目描述:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保 证奇数和奇数,偶数和偶数之间的相对位置不变。
思路:时间复杂度O(n),先用一个LinedList吧奇数记录下来,在用一个LinedList把偶数记录下来,再遍历他们装回去,相当于遍历两边;如果用数组的话得遍历三遍;
程序:
Copy:
public void reOrderArray(int [] array) {
int []copy=Arrays.copyOf(array,array.length);
int i=0;
for(int j=0;j<array.length;j++){
if((copy[j]&1)==1)//如果是奇数
array[i++]=copy[j];
}
for(int j=0;j<array.length;j++){
if((copy[j]&1)==0)//如果是偶数
array[i++]=copy[j];
}
}
public void reOrderArray(int [] array) {
LinkedList<Integer> first=new LinkedList<>();
LinkedList<Integer> second=new LinkedList<>();
for(int i=0;i<array.length;i++){
if((array[i]&1)==1)//奇数
first.add(array[i]);
else
second.add(array[i]);
}
int i=0;
for(Integer num:first){
array[i++]=num;
}
for(Integer num:second){
array[i++]=num;
}
}