经典算法题剖析:按奇偶排序数组

我们先来看题目描述:

给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。

返回满足此条件的 任一数组 作为答案。

示例 1:

复制代码
输入:nums = [3,1,2,4]
输出:[2,4,3,1]
解释:[4,2,3,1]、[2,4,1,3] 和 [4,2,1,3] 也会被视作正确答案。

示例 2:

复制代码
输入:nums = [0]
输出:[0]

提示:

  • 1 <= nums.length <= 5000
  • 0 <= numsi <= 5000

解决方案

方法:两次遍历

思路和算法

新建一个数组 res 用来保存排序完毕的数组。遍历两次 nums,第一次遍历时把所有偶数依次追加到 res 中,第二次遍历时把所有奇数依次追加到 res 中。

代码

Python3

复制代码
class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        return [num for num in nums if num % 2 == 0] + [num for num in nums if num % 2 == 1]

Java

复制代码
class Solution {
    public int[] sortArrayByParity(int[] nums) {
        int n = nums.length, index = 0;
        int[] res = new int[n];
        for (int num : nums) {
            if (num % 2 == 0) {
                res[index++] = num;
            }
        }
        for (int num : nums) {
            if (num % 2 == 1) {
                res[index++] = num;
            }
        }
        return res;
    }
}

C#

复制代码
public class Solution {
    public int[] SortArrayByParity(int[] nums) {
        int n = nums.Length, index = 0;
        int[] res = new int[n];
        foreach (int num in nums) {
            if (num % 2 == 0) {
                res[index++] = num;
            }
        }
        foreach (int num in nums) {
            if (num % 2 == 1) {
                res[index++] = num;
            }
        }
        return res;
    }
}
相关推荐
罗西的思考9 小时前
【Agentic RL】Dressage Staleness 控制深度分析
人工智能·算法·机器学习
quaer10 小时前
弗洛伊德算法--判圈法寻找环的入口O(n) O(1)
数据结构·算法
高晶11 小时前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy11 小时前
大数计算思路
算法
高晶11 小时前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗12 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李12 小时前
反向传播计算梯度举例
算法
niyongsheng12 小时前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
302wanger13 小时前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法
lisw0513 小时前
微分与积分的本质区别解析
算法·数学建模·极限编程