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;
    }
};
相关推荐
AI工程架构师6 小时前
通常说算力是多少 FLOPS,怎么理解,GPU和CPU为什么差异这么大
算法
不想写代码的星星7 小时前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
祈安_7 小时前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法
归去_来兮20 小时前
拉格朗日插值算法原理及简单示例
算法·数据分析·拉格朗日插值
千寻girling1 天前
Python 是用来做 AI 人工智能 的 , 不适合开发 Web 网站 | 《Web框架》
人工智能·后端·算法
颜酱1 天前
一步步实现字符串计算器:从「转整数」到「带括号与优化」
javascript·后端·算法
不想写代码的星星1 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
CoovallyAIHub2 天前
语音AI Agent编排框架!Pipecat斩获10K+ Star,60+集成开箱即用,亚秒级对话延迟接近真人反应速度!
深度学习·算法·计算机视觉
NineData2 天前
数据库管理工具NineData,一年进化成为数万+开发者的首选数据库工具?
运维·数据结构·数据库
木心月转码ing2 天前
Hot100-Day14-T33搜索旋转排序数组
算法