Partition an integers array into odd number first and even number second.
Example
Given [1, 2, 3, 4]
, return [1, 3, 2, 4]
Challenge
双指针,一个指针从左至右寻找偶数,另一个从右至左寻找基数。找到之后互换。
Do it in-place.
public class Solution {
/**
* @param nums: an array of integers
* @return: nothing
*/
public void partitionArray(int[] nums) {
int posOdd = 0, posEven = nums.length - 1;
while(true) {
while(posOdd < nums.length && nums[posOdd] % 2 == 1) posOdd++;
while(posEven >= 0 && nums[posEven] % 2 == 0) posEven--;
if(posOdd >= posEven) return;
else {
int tmp = nums[posEven];
nums[posEven] = nums[posOdd];
nums[posOdd] = tmp;
}
}
}
}