Bootstrap

LeetCode 0922.按奇偶排序数组 II:O(1)空间复杂度-一次遍历双指针

【LetMeFly】922.按奇偶排序数组 II:O(1)空间复杂度-一次遍历双指针

力扣题目链接:https://leetcode.cn/problems/sort-array-by-parity-ii/

给定一个非负整数数组 nums,  nums 中一半整数是 奇数 ,一半整数是 偶数

对数组进行排序,以便当 nums[i] 为奇数时,i 也是 奇数 ;当 nums[i] 为偶数时, i 也是 偶数

你可以返回 任何满足上述条件的数组作为答案

 

示例 1:

输入:nums = [4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。

示例 2:

输入:nums = [2,3]
输出:[2,3]

 

提示:

  • 2 <= nums.length <= 2 * 104
  • nums.length 是偶数
  • nums 中一半是偶数
  • 0 <= nums[i] <= 1000

 

进阶:可以不使用额外空间解决问题吗?

解题方法:双指针

使用两个指针分别指向奇数下标和偶数下标。

当偶数下标指针不越界时,如果偶数下标指针指向的是偶数,就右移到下一个偶数下标;否则如果奇数下标指针指向的是奇数,就右移到下一个奇数下标;否则(奇数指针指偶数,偶数指针指奇数)就交换二者并集体右移。

为什么“当偶数下标指针不越界”这一个条件就够了?因为偶数下标越界时,说明偶数下标的元素全部符合,也说明奇数下标的元素全部合规了。

  • 时间复杂度 O ( l e n ( n u m s ) ) O(len(nums)) O(len(nums))
  • 空间复杂度 O ( 1 ) O(1) O(1)

AC代码

C++
/*
 * @Author: LetMeFly
 * @Date: 2025-02-04 22:15:09
 * @LastEditors: LetMeFly.xyz
 * @LastEditTime: 2025-02-04 22:23:51
 */
class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& nums) {
        for (int i = 0, j = 1; i < nums.size();) {
            if (nums[i] % 2 == 0) {
                i += 2;
            } else if (nums[j] % 2) {
                j += 2;
            } else {
                swap(nums[i], nums[j]);
                i += 2;
                j += 2;
            }
        }
        return nums;
    }
};
Python
'''
Author: LetMeFly
Date: 2025-02-04 22:25:05
LastEditors: LetMeFly.xyz
LastEditTime: 2025-02-04 22:26:17
'''
from typing import List

class Solution:
    def sortArrayByParityII(self, nums: List[int]) -> List[int]:
        i, j = 0, 1
        while i < len(nums):
            if nums[i] % 2 == 0:
                i += 2
            elif nums[j] % 2:
                j += 2
            else:
                nums[i], nums[j] = nums[j], nums[i]
                i += 2
                j += 2
        return nums
Java
/*
 * @Author: LetMeFly
 * @Date: 2025-02-04 22:25:10
 * @LastEditors: LetMeFly.xyz
 * @LastEditTime: 2025-02-04 22:28:26
 */
class Solution {
    public int[] sortArrayByParityII(int[] nums) {
        for (int i = 0, j = 1; i < nums.length;) {
            if (nums[i] % 2 == 0) {
                i += 2;
            } else if (nums[j] % 2 != 0) {
                j += 2;
            } else {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                i += 2;
                j += 2;
            }
        }
        return nums;
    }
}
Go
/*
 * @Author: LetMeFly
 * @Date: 2025-02-04 22:25:07
 * @LastEditors: LetMeFly.xyz
 * @LastEditTime: 2025-02-04 22:32:30
 */
package main

func sortArrayByParityII(nums []int) []int {
    for i, j := 0, 1; i < len(nums); {
		if nums[i] % 2 == 0 {
			i += 2
		} else if nums[j] % 2 == 1 {
			j += 2
		} else {
			nums[i], nums[j] = nums[j], nums[i]
			i += 2
			j += 2
		}
	}
	return nums
}

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/145445952

;