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;
    }
};
相关推荐
DeltaTime6 分钟前
三 视图变换, 投影变换, 正交投影, 透视投影
c++·图形渲染
云技纵横6 分钟前
Redis 数据结构底层与 Hash 优于 JSON 的工程实践
数据结构·redis·哈希算法
superman超哥6 分钟前
仓颉Result类型的错误处理模式深度解析
c语言·开发语言·c++·python·仓颉
八月的雨季 最後的冰吻8 分钟前
FFmepg-- 38-ffplay源码-缓冲区 audio_buf调试
c++·ffmpeg·音视频
会思考的猴子10 分钟前
UE5 C++ 笔记 GameplayAbilitySystem人物角色
c++·笔记·ue5
Binky67813 分钟前
力扣--贪心篇(1)
数据结构·算法·leetcode
sinat_2554878114 分钟前
文件I/O流
java·jvm·算法
ht巷子14 分钟前
Qt:信号与槽
开发语言·c++·qt
千里马-horse15 分钟前
Checker Tool
c++·node.js·napi
北辰水墨16 分钟前
【算法篇】单调栈的学习
c++·笔记·学习·算法·单调栈