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;
    }
};
相关推荐
迷海几秒前
C++内存对齐
开发语言·c++
cxr8284 分钟前
细胞球运动追踪的卡尔曼滤波与力场插值算法 —— 活体内微米级颗粒实时定位与轨迹预测系统
算法
炘爚4 分钟前
C++(流类:istream /ostream/istringstream /ostringstream)
开发语言·c++·算法
!停10 分钟前
C++入门—内存管理
java·jvm·c++
A.A呐11 分钟前
【C++第二十五章】智能指针
c++
倒酒小生11 分钟前
日拱一卒,滴水穿石
数据结构
塞北山巅13 分钟前
Windows 下基于 MSYS2 搭建 C++ 开发环境:从安装到配置全指南
开发语言·c++·windows
海参崴-14 分钟前
C语言与C++语言发展历史详解
java·c语言·c++
爱睡懒觉的焦糖玛奇朵14 分钟前
【工业级落地算法之打架斗殴检测算法详解】
人工智能·python·深度学习·学习·算法·yolo·计算机视觉
练习时长一年22 分钟前
后端开发常用的skill推荐
人工智能·算法·职场和发展