Partition Array by Odd and Even
Partition an integers array into odd number first and even number second.
Have you met this question in a real interview? Yes
Example
Challenge
Tags
Related Problems
Notes
Given [1, 2, 3, 4], return [1, 3, 2, 4]
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;
}
}
}
}