描述
分割一个整数数组,使得奇数在前偶数在后。
样例
给定 [1, 2, 3, 4],返回 [1, 3, 2, 4]。
挑战
分割一个整数数组,使得奇数在前偶数在后。
样例
给定 [1, 2, 3, 4],返回 [1, 3, 2, 4]。
挑战
在原数组中完成,不使用额外空间。
分析
找一个记录存放奇数位置的变量odd_index,如果当前位置i是奇数,则交换位置。全部遍历一遍,前odd_index个数全部是奇数。这里时间复杂度为O(n)。
程序
class Solution { public: /* * @param nums: an array of integers * @return: nothing */ void partitionArray(vector<int> &nums) { // write your code here if(nums.empty()) return; int odd_index = 0; for(int i = 0; i < nums.size(); i++){ if(nums[i] % 2 != 0){ swap(nums[i], nums[odd_index]); odd_index++; } } return; } };