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;
    }
};
相关推荐
CodeOfCC5 分钟前
C++ 基于kmp解析nalu
c++·音视频·实时音视频·h.265·h.264
Sheep Shaun5 分钟前
STL中的map和set:红黑树的优雅应用
开发语言·数据结构·c++·后端·c#
算法与编程之美8 分钟前
探索不同的损失函数对分类精度的影响.
人工智能·算法·机器学习·分类·数据挖掘
H_BB8 分钟前
leetcode160:相交链表
数据结构·算法·链表
浅川.2512 分钟前
STL专项:queue 队列
数据结构·stl·queue
前端小L38 分钟前
贪心算法专题(十五):借位与填充的智慧——「单调递增的数字」
javascript·算法·贪心算法
前端小L1 小时前
贪心算法专题(十四):万流归宗——「合并区间」
javascript·算法·贪心算法
1001101_QIA1 小时前
【C++笔试题】递归判断数组是否是递增数组
开发语言·c++
hans汉斯1 小时前
基于数据重构与阈值自适应的信用卡欺诈不平衡分类模型研究
大数据·算法·机器学习·重构·分类·数据挖掘·机器人
ZPC82101 小时前
FANUC 机器人 PR 寄存器
人工智能·python·算法·机器人