数组-奇偶分割数组-简单

描述
分割一个整数数组,使得奇数在前偶数在后。

样例
给定 [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;
    }
};


猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/80683553