LeetCode 题解工作台
使数组平衡的最少移除数目
给你一个整数数组 nums 和一个整数 k 。 如果一个数组的 最大 元素的值 至多 是其 最小 元素的 k 倍,则该数组被称为是 平衡 的。 你可以从 nums 中移除 任意 数量的元素,但不能使其变为 空 数组。 返回为了使剩余数组平衡,需要移除的元素的 最小 数量。 注意: 大小为 1 的数组…
0
题型
6
代码语言
0
相关题
当前训练重点
中等 · minimum·removals·to·balance·数组·core·interview·pattern
答案摘要
我们首先对数组进行排序,然后我们从小到大枚举每个元素 作为平衡数组的最小值,那么平衡数组的最大值 必须满足 $\textit{max} \leq \textit{nums}[i] \times k$。因此,我们可以使用二分查找来找到第一个大于 $\textit{nums}[i] \times k$ 的元素的下标 ,那么此时平衡数组的长度为 $j - i$,我们记录下最大的长度 ,最后的答案就是…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 minimum·removals·to·balance·数组·core·interview·pattern 题型思路
题目描述
给你一个整数数组 nums 和一个整数 k。
如果一个数组的 最大 元素的值 至多 是其 最小 元素的 k 倍,则该数组被称为是 平衡 的。
你可以从 nums 中移除 任意 数量的元素,但不能使其变为 空 数组。
返回为了使剩余数组平衡,需要移除的元素的 最小 数量。
注意:大小为 1 的数组被认为是平衡的,因为其最大值和最小值相等,且条件总是成立。
示例 1:
输入:nums = [2,1,5], k = 2
输出:1
解释:
- 移除
nums[2] = 5得到nums = [2, 1]。 - 现在
max = 2,min = 1,且max <= min * k,因为2 <= 1 * 2。因此,答案是 1。
示例 2:
输入:nums = [1,6,2,9], k = 3
输出:2
解释:
- 移除
nums[0] = 1和nums[3] = 9得到nums = [6, 2]。 - 现在
max = 6,min = 2,且max <= min * k,因为6 <= 2 * 3。因此,答案是 2。
示例 3:
输入:nums = [4,6], k = 2
输出:0
解释:
- 由于
nums已经平衡,因为6 <= 4 * 2,所以不需要移除任何元素。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 1091 <= k <= 105
解题思路
方法一:排序 + 二分查找
我们首先对数组进行排序,然后我们从小到大枚举每个元素 作为平衡数组的最小值,那么平衡数组的最大值 必须满足 。因此,我们可以使用二分查找来找到第一个大于 的元素的下标 ,那么此时平衡数组的长度为 ,我们记录下最大的长度 ,最后的答案就是数组长度减去 。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def minRemoval(self, nums: List[int], k: int) -> int:
nums.sort()
cnt = 0
for i, x in enumerate(nums):
j = bisect_right(nums, k * x)
cnt = max(cnt, j - i)
return len(nums) - cnt
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Sorting is likely expected to simplify the ratio check.
- question_mark
Sliding window hints at using two pointers to maximize the valid subarray length.
- question_mark
They may probe edge cases like duplicates or large k values to check correctness.
常见陷阱
外企场景- error
Forgetting that removing elements cannot leave the array empty.
- error
Incorrectly checking the k-times condition without sorting first.
- error
Using nested loops leading to O(n^2) instead of two-pointer linear scan after sorting.
进阶变体
外企场景- arrow_right_alt
Find the minimum removals when the array must remain contiguous after removal.
- arrow_right_alt
Balance the array using only even-indexed elements with the k-times condition.
- arrow_right_alt
Compute the minimum removals when elements can be doubled or halved instead of removed.