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;
    }
};
相关推荐
北邮刘老师12 小时前
智能体治理:人工智能时代信息化系统的全新挑战与课题
大数据·人工智能·算法·机器学习·智能体互联网
w-w0w-w13 小时前
C++模板参数与特化全解析
开发语言·c++
AlenTech13 小时前
155. 最小栈 - 力扣(LeetCode)
算法·leetcode·职场和发展
mit6.82413 小时前
正反两次扫描|单调性cut
算法
Yzzz-F13 小时前
牛客小白月赛127 E
算法
大锦终13 小时前
递归回溯综合练习
c++·算法·深度优先
Keep__Fighting14 小时前
【神经网络的训练策略选取】
人工智能·深度学习·神经网络·算法
晚风吹长发14 小时前
初步了解Linux中的动静态库及其制作和使用
linux·运维·服务器·数据结构·c++·后端·算法
sin_hielo14 小时前
leetcode 3453(二分法)
算法
坚持不懈的大白14 小时前
Leetcode学习笔记
笔记·学习·leetcode