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;
    }
};
相关推荐
徐小夕23 分钟前
花了一周,3亿tokens,我开源了一款 Word 文档智能审查平台,文稿自动质检+可视化分析,告别低效人工审核
前端·算法·github
可编程芯片开发2 小时前
UPFC统一潮流控制器的simulink建模与仿真
算法
小小仙子2 小时前
矢量网络分析仪如何测试S参数的?
人工智能·算法·机器学习
code bean3 小时前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
中微极客4 小时前
降维算法75倍加速:从PCA到稀疏字典学习的工程实践
人工智能·学习·算法
storyseek4 小时前
前缀和实现Kogge-Stone算法
数据结构·算法
ziguo11224 小时前
深入浅出 C/C++ 数据类型:从入门到踩坑
linux·c语言·c++·windows·visual studio
元Y亨H5 小时前
开发者必须掌握的十大核心算法
算法
元Y亨H5 小时前
深度解构:数据结构与算法的理论基石与工程演进
数据结构·算法