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.
非常典型的two pointer: 一个左指针,一个右指针, 当left 指针所指为奇数则向前继续,如果为偶数则交换left, right指针所指数,并且right向左走一步,代码如下:
void partitionArray(vector<int> &nums) {
// write your code here
if(nums.size() == 0 || nums.size() == 1){
return;
}
// 典型的对冲指针
int left = 0;
int right = nums.size() - 1;
while(left < right){
if(nums[left] % 2 == 1){
left++;
}
else{
exchange(nums, left, right);
right--;
}
}
}
void exchange(vector<int>& num, int left, int right){
int temp = num[left];
num[left] = num[right];
num[right] = temp;
}