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;
    }
};
相关推荐
闻缺陷则喜何志丹3 分钟前
【栈 递归】P8650 [蓝桥杯 2017 省 A] 正则问题|普及+
c++·数学·蓝桥杯·递归·
苏宸啊8 分钟前
vecto底层模拟实现
c++
80530单词突击赢11 分钟前
STLVector底层原理与高效运用
数据结构·算法
一切尽在,你来12 分钟前
C++多线程教程-1.2.2 C++标准库并发组件的设计理念
开发语言·c++
haluhalu.14 分钟前
LeetCode---基础算法刷题指南
数据结构·算法·leetcode
iAkuya20 分钟前
(leetcode)力扣100 58组合总和(回溯)
算法·leetcode·职场和发展
80530单词突击赢21 分钟前
C++关联容器深度解析:set/map全攻略
java·数据结构·算法
m0_5613596722 分钟前
代码热更新技术
开发语言·c++·算法
兩尛28 分钟前
c++知识点1
java·开发语言·c++
冉佳驹36 分钟前
C++11 ——— 列表初始化、移动语义、可变参数模板、lamdba表达式、function包装器和bind包装器
c++·可变参数模板·移动构造·移动赋值·function包装器·bind包装器·lamdba表达式