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;
    }
};
相关推荐
林文韬3273 分钟前
逐位二进制拼接 → 翻转 → 去头零 → 消邻重
算法
变量未定义~3 分钟前
单点修改、区间求和(模板)、区间修改,单点查询(模板)
数据结构·算法
weixin_4684668514 分钟前
SURF 图像特征提取算法新手实战指南
图像处理·人工智能·算法·机器视觉·surf·sift
Lumos_7771 小时前
程序的诞生
c++
basketball6161 小时前
C++ static_cast 完全解析
开发语言·c++
weixin_468466851 小时前
支持向量机新手实战指南
人工智能·python·算法·机器学习·支持向量机
LinHenrY12271 小时前
数据结构(二叉树)
数据结构
Lumbrologist1 小时前
【C++】零基础入门 · 第 12 节:模板与 STL 入门
开发语言·c++
炸薯条!2 小时前
树--二叉树--堆
数据结构
weixin_468466852 小时前
机器学习之决策树新手实战指南
人工智能·python·算法·决策树·机器学习·ai