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;
    }
};
相关推荐
叩码以求索6 小时前
使用next数组加速匹配过程
java·数据结构·算法
aaPIXa6226 小时前
C++ 质量前置检查:clang-format 与 clang-tidy 实践指南
开发语言·c++
余额瞒着我当琳6 小时前
C++ 基础核心概念精讲:引用、内联与 nullptr
java·开发语言·c++
名字还没想好☜6 小时前
Go 内存逃逸分析:什么时候变量跑到堆上
开发语言·算法·性能优化·golang·go·内存逃逸
li星野6 小时前
滑动窗口五题通关:从食堂打饭到上下文窗口——算法与大模型的内存管理哲学
算法
Ivanqhz6 小时前
NFM(神经因子分解机)
开发语言·javascript·人工智能·算法·蓝桥杯
深圳市快瞳科技有限公司6 小时前
从人工录入到秒级识别:保单OCR识别厂家选型指南
人工智能·算法·计算机视觉·ocr
小欣加油6 小时前
leetcode1331 数组序号转换
数据结构·c++·算法·leetcode·职场和发展
学究天人6 小时前
数学公理体系大全:第五章 序数与基数理论:超限算术与集合的大小
人工智能·线性代数·算法·机器学习·数学建模·原型模式
阿米亚波6 小时前
【C++ STL】std::deque
数据结构·c++·笔记·算法·stl