奇偶分割数组
题目
分割一个整数数组,使得奇数在前偶数在后。
样例
给定 [1, 2, 3, 4],返回 [1, 3, 2, 4]。
挑战
在原数组中完成,不使用额外空间。
题解
首尾双指针遍历,start指针查找偶数,end指针查找奇数,然后进行交换。
public class Solution {
/**
* @param nums: an array of integers
* @return: nothing
*/
public void partitionArray(int[] nums) {
int start = 0;
int end = nums.length-1;
while (start < end)
{
while ((nums[start] & 1) == 1)
{
start++;
}
while ((nums[end] & 1) == 0)
{
end--;
}
if(start < end)
{
nums[start]=nums[start]+nums[end];
nums[end]=nums[start]-nums[end];
nums[start]=nums[start]-nums[end];
}
}
}
}
Last Update 2016.9.13