78 奇偶分割数组(Partition Array by Odd and Even)

1 题目

题目:奇偶分割数组(Partition Array by Odd and Even)
描述:分割一个整数数组,使得奇数在前偶数在后。

lintcode题号——373,难度——easy

样例1:

输入: [1,2,3,4]
输出: [1,3,2,4]

样例2:

输入: [1,4,2,3,5,6]
输出: [1,3,5,4,2,6]

2 解决方案

2.1 思路

  使用对向双指针的方式,两个指针分别从头尾开始向中间走,左指针找偶数,右指针找奇数,然后互相交换,将奇数排在左指针的位置,偶数排在右指针的位置,进行一轮即可分割完。

2.2 时间复杂度

  时间复杂度为O(n)。

2.3 空间复杂度

  空间复杂度为O(1)。

3 源码

细节:

  1. 使用对向双指针的方式,奇数的往左交换,偶数的往右交换,比对一轮即可。

C++版本:

/*
* @param nums: an array of integers
* @return: nothing
*/
void partitionArray(vector<int> &nums) {
    // write your code here
    if (nums.size() < 2)
    {
        return;
    }

    int left = 0;
    int right = nums.size() - 1;
    while (left < right)
    {
        if (nums.at(left) % 2 != 0)
        {
            left++;
            continue;
        }
        if (nums.at(right) % 2 == 0)
        {
            right--;
            continue;
        }

        if (left < right)
        {
            swap(nums.at(left++), nums.at(right--));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/SeeDoubleU/article/details/124642282