题目
该系列文章题目和思路均参考自:《剑指Offer》- Page 129
解法
思路1:看到该问题,如果对快速排序的循环不变式比较熟悉的话,就很容易想到快速排序中的partition方法,其中就是对数组根据不同的条件进行划分的过程。
在快速排序中,三个指针将数组划分为三个区域,其中r指向数组最后一个元素,i初始指向数组开始的前一个元素,j指向数组中待排序的元素。因此它的循环不变式为:
- array[start, i]为小于array[r]的元素
- array[i+1, j-1]为大于array[r]的元素
- array[j, r-1]为待排序的元素
类似的思路,将partition中的对元素条件的判断进行修改,即可改为解决此类问题的通用方法。
/**
* 思路1,仿照Partition算法的思想
* @param array
* @return
*/
private static int[] reorderOddEvent(int[] array) {
if (array == null || array.length == 0) {
return null;
}
int i = -1;
for (int j = 0; j < array.length; j++) {
if (array[j] % 2 != 0) {
i = i + 1;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
return array;
}
思路2:使用前后两个指针start和end,start从数组的开头进行遍历,直到指向第一个偶数,end从数组的结尾进行遍历直到指向第一个奇数,然后将两个指针指向的数组元素进行交换,完成后,start继续向后移动找到后一个偶数,end继续向前移动找到前一个奇数,继续交换,直到不满足start<end时,即将整个数组遍历完毕。
/**
* 思路2
* @param array
* @return
*/
private static int[] reorderOddEvent_solution2(int[] array) {
if (array == null || array.length == 0) {
return null;
}
int start = 0;
int end = array.length - 1;
while (start < end) {
// 移动start,直到指向偶数
while (start < end && array[start] % 2 != 0) {
start++;
}
// 移动end,直到指向奇数
while (start < end && array[end] % 2 == 0) {
end--;
}
// 交换两个位置上的元素
if (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
}
}
return array;
}