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;
    }
};
相关推荐
一条大祥脚几秒前
Codeforces Round 1098 (Div. 2)
算法·深度优先
时空自由民.4 分钟前
平衡车PID控制系统(豆包版本)
算法
sno_guo23 分钟前
直播抠图技术100谈之25---调色中曲线是最优解
人工智能·算法·机器学习·直播·内容运营·obs抠图·直播技术
故事和你9127 分钟前
洛谷-【图论2-2】最短路1
开发语言·数据结构·c++·算法·动态规划·图论
Simple-Soft31 分钟前
指针的高级应用与技巧 - C语言的灵魂
c语言·数据结构·算法
南宫萧幕36 分钟前
Simulink 从零搭建 HEV ECMS 环境:模块解析、排坑指南与智能算法接口预留
人工智能·算法·matlab·汽车·控制
子豪-中国机器人39 分钟前
词云与条形码答案
算法
杰之行40 分钟前
Fast-DDS 接收数据完整时序分析
c++·人工智能
闲人编程41 分钟前
Agent的评估体系(AgentEval):如何判断一个Agent好坏?
大数据·人工智能·python·算法·agent·智能体·swe
沫璃染墨1 小时前
红黑树完全指南:从核心原理到插入验证全实现
开发语言·c++·算法