题目
分割一个整数数组,使得奇数在前偶数在后。http://www.lintcode.com/zh-cn/problem/partition-array-by-odd-and-even/
分析
很简单的一道题目,从后往前找奇数,从前往后找偶数,如果奇数的下标大于偶数的下标,则两者交换,继续重复该动作;否则表明无需再处理。
快速判断奇数、偶数,只需要考察 number & 0x01 == 0x01 是否成立
代码
public class Solution {
boolean isOdd(int val) {
return (val & 0x1) == 0x01;
}
int findNext(int[] array, int start, int end, int step, boolean isOdd) {
for ( ; start < end ? start < end : start > end; start += step) {
boolean result = this.isOdd(array[start]);
if (isOdd) {
if (result) return start;
continue;
} else {
if (result) continue;
return start;
}
}
return -1;
}
/*
* @param nums: an array of integers
* @return: nothing
*/
public void partitionArray(int[] nums) {
// write your code here
for(int i=0, j=nums.length-1; i