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

我们先来看题目描述:

给你一个整数数组 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;
    }
}
相关推荐
longlongzihan4 小时前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
封印师请假去地球钓鱼4 小时前
边解边变的问题:从“决策依赖“一词出发
人工智能·算法
今晚打老虎5 小时前
c++之提高A(前缀和)(第三课)
数据结构·c++·算法
不会就选b6 小时前
算法日常・每日刷题--<贪心>26
数据结构·算法
hetao17338378 小时前
2026-09-29 hetao1733837 的刷题记录
c++·算法
欣欣之王来了8 小时前
AI合规专项:AI算法透明度的合规要求
人工智能·算法
wzdark8 小时前
分块思想在算法优化中的实践与应用4
算法
Because_of_Her19 小时前
dfs-洪水填充技巧
笔记·算法·深度优先·洪水填充
小静AI工程实验室9 小时前
RSA 算法详解:从模幂原理到 OAEP 加密、PSS 签名与 Python 实验
python·算法
xzal129 小时前
GESP Python笔记
笔记·python·算法