分割一个整数数组,使得奇数在前偶数在后。
样例
给定 [1, 2, 3, 4]
,返回 [1, 3, 2, 4]
。
挑战
在原数组中完成,不使用额外空间。
解题思路1:
双指针法。类似于Lintcode 213:字符串压缩,设置两个指针i, j,从头遍历,i指向第一次出现偶数,j从i开始指向第一次出现的奇数,然后将两者指向的元素交换,继续。
class Solution {
public:
/*
* @param nums: an array of integers
* @return: nothing
*/
void partitionArray(vector<int> &nums)
{
// write your code here
for(int i=0,j=0;i<nums.size();j=i)
{
if(nums[i]%2 == 0)
{
while(nums[j]%2 == 0 && j<nums.size())
j++;
swap(nums[i],nums[j]);
}
i++;
}
}
};
解题思路2:
同样采用双指针,只是一个指针在首,一个指针在尾。
class Solution {
public:
/*
* @param nums: an array of integers
* @return: nothing
*/
void partitionArray(vector<int> &nums)
{
// write your code here
int i=0;
int j=nums.size()-1;
while(i<j)
{
if(nums[i]%2 == 0)
{
swap(nums[i],nums[j]);
j--;
}
else
i++;
}
}
};
JAVA代码:
public class Solution {
/*
* @param nums: an array of integers
* @return: nothing
*/
public void partitionArray(int[] nums) {
// write your code here
int i = 0;
int j = nums.length-1;
while(i<j){
if(nums[i]%2 == 0){
swap(nums , i , j--);
}else{
i++;
}
}
}
public void swap(int[] nums , int i , int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}