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;
    }
};
相关推荐
自信150413057591 天前
初学者小白复盘15之指针(4)
c语言·数据结构·算法
郝学胜-神的一滴1 天前
Cesium绘制线:从基础到高级技巧
前端·javascript·程序人生·线性代数·算法·矩阵·图形渲染
AA陈超1 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-13 属性菜单 - 边框值
c++·游戏·ue5·游戏引擎·虚幻
东皇太星1 天前
机器学习概念,算法原理及应用
算法·机器学习·梯度下降法
.格子衫.1 天前
021数据结构之并查集——算法备赛
数据结构·算法
姝孟1 天前
C++学习——类与对象详细知识点总结
c++·笔记·学习
im_AMBER1 天前
Leetcode 35
笔记·学习·算法·leetcode
码农多耕地呗1 天前
力扣101.对称二叉树(java)
算法·leetcode
小龙报1 天前
《算法通关指南之C++编程篇(5)----- 条件判断与循环(下)》
c语言·开发语言·c++·算法·visualstudio·学习方法·visual studio
郝学胜-神的一滴1 天前
C++ STL(标准模板库)深度解析:从基础到实践
linux·服务器·开发语言·c++·算法