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;
    }
};
相关推荐
tankeven2 分钟前
贪心算法(Greedy Algorithm)详解:从理论到C++实践
c++·算法
Hesionberger3 分钟前
LeetCode72.编辑距离(多维动态规划)
java·开发语言·c++·python·算法
lwf0061644 分钟前
逻辑回归学习笔记-梯度下降求解回归方程
算法·机器学习·逻辑回归
郝学胜-神的一滴5 分钟前
从底层看透Linux高性能服务器:epoll自定义封装与超时清理实战
linux·服务器·c++·网络协议·tcp/ip·unix
人道领域10 分钟前
【LeetCode刷题日记】1047:双栈法与双指针法巧妙消除相邻重复字符
java·算法·leetcode·职场和发展
切糕师学AI10 分钟前
布隆过滤器(Bloom Filter)技术详解
数学·算法
礼拜天没时间.15 分钟前
力扣热题100实战 | 第33期:搜索旋转排序数组——二分查找的变体艺术
算法·leetcode·职场和发展·旋转数组·搜索旋转排序数组
Jenlybein30 分钟前
用 uv 替代 conda,速度飙升(从 0 到 1 开始使用 uv)
后端·python·算法
400分30 分钟前
LangChain 与大模型技术全链路详解
算法·架构
电科一班林耿超31 分钟前
第 14 课:动态规划(DP)—— 算法思想的巅峰,面试的终极分水岭
数据结构·算法·动态规划