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

我们先来看题目描述:

给你一个整数数组 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;
    }
}
相关推荐
AI小码1 小时前
WAIC 2026前瞻:AI产业进入拼落地的下半场
人工智能·算法·ai·程序员·大模型·编程·智能体
珠海西格电力2 小时前
零碳园区数据应用的具体场景有哪些?
大数据·人工智能·算法·架构·能源
geovindu2 小时前
CSharp: Dijkstra Algorithms
开发语言·后端·算法·c#
学逆向的3 小时前
汇编——位运算
开发语言·汇编·算法·网络安全
可编程芯片开发3 小时前
基于simulink的PEM燃料电池控制系统建模与仿真,对比PID,积分分离以及滑模控制器
算法
学究天人3 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷2)
算法·数学建模·动态规划·图论·抽象代数·拓扑学
玛卡巴卡ldf4 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
wanzehongsheng4 小时前
零碳产业园光伏园区光伏电站追踪对比固定:发电增益技术边界分析
算法·光伏发电·光伏·零碳园区·太阳能追光·低碳环保·追踪电站
KobeSacre4 小时前
CyclicBarrier 源码
java·jvm·算法