题目来源:LintCode
原题地址:http://www.lintcode.com/zh-cn/problem/partition-array-by-odd-and-even/
题目:
分割一个整数数组,使得奇数在前偶数在后。
您在真实的面试中是否遇到过这个题?
Yes
样例
给定 [1, 2, 3, 4]
,返回 [1, 3, 2, 4]
。
挑战
在原数组中完成,不使用额外空间。
难度级别:
容易
容易
思路分析:
实现代码:
class Solution
{
public:
/**
* @param nums: a vector of integers
* @return: nothing
*/
void partitionArray(vector<int> &nums)
{
int i = 0, j = nums.size() - 1;
while (i < j)
{
if (nums[i] % 2 == 0)
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j--;
} else
{
i++;
}
}
return;
}
};
代码说明:
一头一尾的双指针方法来解这个题,其时间复杂度是O(n)的。
一头一尾的双指针方法来解这个题,其时间复杂度是O(n)的。