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;
    }
};
相关推荐
七颗糖很甜7 分钟前
基于 OpenCV 的 FY2 云顶图云块追踪算法实现
人工智能·opencv·算法
__Wedream__8 分钟前
NTIRE 2026 Challenge on Efficient Super-Resolution——冠军方案解读
人工智能·深度学习·算法·计算机视觉·超分辨率重建
yong15858553439 分钟前
Linux C++ 中的 volatile变量在多线程环境下进行运算的问题
c语言·c++
FL162386312912 分钟前
基于深度学习mediape实现人员跌倒人体姿势跌倒检测算法源码+说明文件
人工智能·深度学习·算法
wangwangmoon_light13 分钟前
1.23 LeetCode总结(树)_一般树
算法·leetcode·职场和发展
小肝一下13 分钟前
c++从入门到跑路——string类
开发语言·c++·职场和发展·string类
被考核重击14 分钟前
基础算法学习
学习·算法
小O的算法实验室17 分钟前
2026年ASOC,学习驱动人工蜂群算法+移动机器人多目标路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
楼田莉子17 分钟前
设计模式:构造器模式
开发语言·c++·后端·学习·设计模式
邪修king21 分钟前
UE5 零基础入门第二弹:让你的几何体 “活” 起来 ——Actor 基础与蓝图交互入门
c++·ue5·交互