LeetCode922. Sort Array By Parity II

文章目录

一、题目

Given an array of integers nums, half of the integers in nums are odd, and the other half are even.

Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

Return any answer array that satisfies this condition.

Example 1:

Input: nums = [4,2,5,7]

Output: [4,5,2,7]

Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Example 2:

Input: nums = [2,3]

Output: [2,3]

Constraints:

2 <= nums.length <= 2 * 104

nums.length is even.

Half of the integers in nums are even.

0 <= nums[i] <= 1000

Follow Up: Could you solve it in-place?

二、题解

cpp 复制代码
class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& nums) {
        int n = nums.size();
        int oddIndex = 1;
        for(int i = 0;i < n;i+=2){
            //存在偶数位上的奇数
            if(nums[i] % 2 == 1){
                //查找奇数位上的偶数
                while(nums[oddIndex] % 2 != 0) oddIndex += 2;
                swap(nums[i],nums[oddIndex]);
            }
        }
        return nums;
    }
};
相关推荐
YL20040426几秒前
027合并两个有序链表
java·数据结构·算法·链表
顶点多余19 分钟前
自定义协议、序列化、反序列化实现
java·linux·开发语言·c++·tcp/ip
MATLAB代码顾问30 分钟前
【智能优化】无穷优化算法(INFO)原理与Python实现
开发语言·python·算法
炽烈小老头32 分钟前
【每天学习一点算法 2026/05/10】合并K个排序链表
学习·算法·链表
Bruce_kaizy33 分钟前
c++ linux环境编程——从应用层到linux内核深入了解文件io的调用机制(爆肝)
linux·c++·c·嵌入式linux·文件io
Zephyr_034 分钟前
java数据结构
java·数据结构
z2005093040 分钟前
C++中的右值引用
开发语言·c++
SilentSamsara42 分钟前
迭代器协议:`__iter__` / `__next__` 的完整执行流程
开发语言·人工智能·python·算法·机器学习
AI科技星42 分钟前
算法联盟ROOT · 全域数学物理卷第20、21、22分册:量子纠缠、隐形场论与时间膨胀
人工智能·算法·数学建模·数据挖掘·机器人
代码中介商1 小时前
C++文件流操作全解析
开发语言·c++