本问题对应的 leetcode 原文链接:剑指 Offer 21. 调整数组顺序使奇数位于偶数前面

问题描述

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分。

示例 1:

输入:nums = [1,2,3,4]
输出:[1,3,2,4] 
注:[3,1,2,4] 也是正确的答案之一。

提示:

  • 0 <= nums.length <= 50000
  • 0 <= nums[i] <= 10000

解题思路

视频讲解直达: 本题视频讲解

代码实现

class Solution {
    public int[] exchange(int[] nums) {
        if(nums == null || nums.length == 0){
            return nums;
        }
        int left = 0;
        int right = nums.length - 1;
        while(left < right){
            while(left < right && nums[left] % 2 != 0) left++;
            while(left < right && nums[right] % 2 != 1) right--;

            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
        }

        return nums;
    }
}

时间复杂度:O(n)
额外空间复杂度:O(1)

Python

class Solution(object):
    def exchange(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if nums is None or len(nums) == 0:
            return nums
        left = 0
        right = len(nums) - 1
        while left < right:
            while left < right and nums[left] % 2 != 0:
                left += 1
            while left < right and nums[right] % 2 != 1:
                right -= 1

            temp = nums[left]
            nums[left] = nums[right]
            nums[right] = temp

        return nums

C++

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        if (nums.empty()) {
            return nums;
        }
        int left = 0;
        int right = nums.size() - 1;
        while (left < right) {
            while (left < right && nums[left] % 2 != 0) left++;
            while (left < right && nums[right] % 2 != 1) right--;

            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
        }

        return nums;
    }
};

Go

func exchange(nums []int) []int {
    if len(nums) == 0 {
        return nums
    }
    left := 0
    right := len(nums) - 1
    for left < right {
        for left < right && nums[left]%2 != 0 {
            left++
        }
        for left < right && nums[right]%2 != 1 {
            right--
        }

        temp := nums[left]
        nums[left] = nums[right]
        nums[right] = temp
    }

    return nums
}

JS

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var exchange = function(nums) {
    if (nums == null || nums.length == 0) {
        return nums;
    }
    let left = 0;
    let right = nums.length - 1;
    while (left < right) {
        while (left < right && nums[left] % 2 !== 0) {
            left++;
        }
        while (left < right && nums[right] % 2 !== 1) {
            right--;
        }

        const temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }

    return nums;
};

发表回复

后才能评论