LeetCode 题解工作台
将数组按照奇偶性转化
给你一个整数数组 nums 。请你按照以下顺序 依次 执行操作,转换 nums : 将每个偶数替换为 0。 将每个奇数替换为 1。 按 非递减 顺序排序修改后的数组。 执行完这些操作后,返回结果数组。 示例 1: 输入: nums = [4,3,2,1] 输出: [0,0,1,1] 解释: 将偶数(…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
我们可以遍历数组 ,统计其中偶数的个数 。然后我们将数组的前 个元素置为 ,剩余的元素置为 。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个整数数组 nums。请你按照以下顺序 依次 执行操作,转换 nums:
- 将每个偶数替换为 0。
- 将每个奇数替换为 1。
- 按 非递减 顺序排序修改后的数组。
执行完这些操作后,返回结果数组。
示例 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 <= 1001 <= nums[i] <= 1000
解题思路
方法一:计数
我们可以遍历数组 ,统计其中偶数的个数 。然后我们将数组的前 个元素置为 ,剩余的元素置为 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.