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;
    }
};
相关推荐
宝贝儿好10 分钟前
【强化学习】第十章:连续动作空间强化学习:随机高斯策略、DPG算法
人工智能·python·深度学习·算法·机器人
isyoungboy14 分钟前
从图像中提取亚像素边缘点
算法
Ljwuhe16 分钟前
类与对象(中)——运算符重载
开发语言·c++
郝学胜-神的一滴17 分钟前
深入理解链表:从基础到实践
开发语言·数据结构·c++·算法·链表·架构
岛雨QA28 分钟前
排序算法「Java数据结构与算法学习笔记6」
数据结构·算法
烟花落o31 分钟前
栈和队列的知识点及代码
开发语言·数据结构·笔记·栈和队列·编程学习
熬夜有啥好32 分钟前
Linux软件编程——综合小练习
linux·算法·目录遍历·fgets·strcpy·linux内核与用户交互·strtok
crescent_悦38 分钟前
C++:Have Fun with Numbers
开发语言·c++
mjhcsp41 分钟前
C++轮廓线 DP:从原理到实战的深度解析
开发语言·c++·动态规划
古译汉书41 分钟前
【IoT死磕系列】Day 7:只传8字节怎么控机械臂?学习工业控制 CANopen 的“对象字典”(附企业级源码)
数据结构·stm32·物联网·http