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 numsi is odd, i is odd, and whenever numsi 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 <= numsi <= 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;
    }
};
相关推荐
浦信仿真大讲堂17 分钟前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠27 分钟前
PCL 生成三棱锥点云
c++·算法·最小二乘法
代码中介商35 分钟前
跳表:高效查找的链表黑科技
数据结构
兰令水38 分钟前
leecodecode【面试150】【2026.6.13打卡-java版本】
java·算法·leetcode
临沂堇43 分钟前
刷题日志 | Leetcode Hot 100 哈希
算法·leetcode·哈希算法
.道阻且长.1 小时前
C++ string 操作指南:接口解析
java·c语言·开发语言·c++
玉小格1 小时前
一次关于Python的总结
算法
伊甸31 小时前
从企业级项目学敏感词过滤:DFA算法与双层缓存实战
java·算法·缓存
laplaya1 小时前
使用 vcpkg 管理 C++ 项目中的依赖
开发语言·c++
bIo7lyA8v1 小时前
算法中的随机化思想及其复杂度收益评估的技术8
算法