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;
    }
};
相关推荐
sel_935 分钟前
【强化学习】Hands-on Modern RL项目实践|OPD 算法完整解析
人工智能·深度学习·算法·机器学习·语言模型
Navigator_Z1 小时前
LeetCode //C - 1209. Remove All Adjacent Duplicates in String II
c语言·算法·leetcode
码匠许师傅3 小时前
【C++ 面试真题】30. 聊聊 C++ 的互斥锁与读写锁
java·c++·面试
ShineWinsu3 小时前
对于 C++:C++14中从变量模板、泛型 Lambda 到并发与字面量的解析
c++·算法
土司大王4 小时前
LeetCode hot100——合并两个有序链表
算法·leetcode·链表
码行山野赴时序归途4 小时前
算法效率的度量(上):时间复杂度中的对数思维
c语言·数据结构·算法
算AI4 小时前
基于LLM的无人机仿真测试:新方法竞赛夺佳绩
人工智能·深度学习·算法·机器学习·ai
kaixin_啊啊5 小时前
专用优化算法LKH
算法
一木 之林6 小时前
四、STL容器与数据结构
开发语言·数据结构·c++