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;
    }
};
相关推荐
zyl76510 小时前
FlashAttention 详解:从 GPU 硬件、普通 Attention 到分块计算与 Online Softmax
算法
爱读书的小胖14 小时前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌14 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
OPEN-F15 小时前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_3077791315 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
AI wins15 小时前
c++新增頭文件
c++
Shadow(⊙o⊙)15 小时前
仿muduo实现高并发服务器——事件就绪管理Channel.hpp
服务器·c++
tomwang032215 小时前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类
小羊没烦恼!15 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
by2099915 小时前
哈希表——快速找到数据:冲突、删除与扩容的实现
数据结构·c++·哈希算法·散列表