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;
    }
};
相关推荐
CAU界编程小白4 小时前
数据结构系列之十大排序算法
数据结构·c++·算法·排序算法
执携4 小时前
数据结构 -- 树(遍历)
数据结构
头发还没掉光光4 小时前
Linux网络初始及网络通信基本原理
linux·运维·开发语言·网络·c++
好学且牛逼的马4 小时前
【Hot100 | 6 LeetCode 15. 三数之和】
算法
橘颂TA4 小时前
【剑斩OFFER】算法的暴力美学——二分查找
算法·leetcode·面试·职场和发展·c/c++
lkbhua莱克瓦244 小时前
Java基础——常用算法4
java·数据结构·笔记·算法·github·排序算法·快速排序
m0_748248025 小时前
揭开 C++ vector 底层面纱:从三指针模型到手写完整实现
开发语言·c++·算法
海盗猫鸥5 小时前
「C++」string类(2)常用接口
开发语言·c++
序属秋秋秋5 小时前
《Linux系统编程之开发工具》【实战:倒计时 + 进度条】
linux·运维·服务器·c语言·c++·ubuntu·系统编程
七夜zippoe5 小时前
Ascend C流与任务管理实战:构建高效的异步计算管道
服务器·网络·算法