LeetCode 题解工作台

将数组按照奇偶性转化

给你一个整数数组 nums 。请你按照以下顺序 依次 执行操作,转换 nums : 将每个偶数替换为 0。 将每个奇数替换为 1。 按 非递减 顺序排序修改后的数组。 执行完这些操作后,返回结果数组。 示例 1: 输入: nums = [4,3,2,1] 输出: [0,0,1,1] 解释: 将偶数(…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

我们可以遍历数组 ,统计其中偶数的个数 。然后我们将数组的前 个元素置为 ,剩余的元素置为 。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums。请你按照以下顺序 依次 执行操作,转换 nums

  1. 将每个偶数替换为 0。
  2. 将每个奇数替换为 1。
  3. 按 非递减 顺序排序修改后的数组。

执行完这些操作后,返回结果数组。

 

示例 1:

输入:nums = [4,3,2,1]

输出:[0,0,1,1]

解释:

  • 将偶数(4 和 2)替换为 0,将奇数(3 和 1)替换为 1。现在,nums = [0, 1, 0, 1]
  • 按非递减顺序排序 nums,得到 nums = [0, 0, 1, 1]

示例 2:

输入:nums = [1,5,1,4,2]

输出:[0,0,1,1,1]

解释:

  • 将偶数(4 和 2)替换为 0,将奇数(1, 5 和 1)替换为 1。现在,nums = [1, 1, 1, 0, 0]
  • 按非递减顺序排序 nums,得到 nums = [0, 0, 1, 1, 1]

 

提示:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 1000
lightbulb

解题思路

方法一:计数

我们可以遍历数组 nums\textit{nums},统计其中偶数的个数 even\textit{even}。然后我们将数组的前 even\textit{even} 个元素置为 00,剩余的元素置为 11

时间复杂度 O(n)O(n),其中 nn 是数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def transformArray(self, nums: List[int]) -> List[int]:
        even = sum(x % 2 == 0 for x in nums)
        for i in range(even):
            nums[i] = 0
        for i in range(even, len(nums)):
            nums[i] = 1
        return nums
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate understands sorting and partitioning techniques.

  • question_mark

    Candidate demonstrates knowledge of array manipulation and space efficiency.

  • question_mark

    Candidate is able to explain the impact of different approaches on time complexity.

warning

常见陷阱

外企场景
  • error

    Confusing the order of even and odd numbers during implementation.

  • error

    Forgetting to maintain the relative order of even and odd numbers.

  • error

    Relying on inefficient sorting techniques when a linear time solution is possible.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change the constraints to allow for larger array sizes.

  • arrow_right_alt

    Add constraints on the range of values for nums.

  • arrow_right_alt

    Require that the array be sorted in descending order after partitioning.

help

常见问题

外企场景

将数组按照奇偶性转化题解:数组·排序 | LeetCode #3467 简单