LeetCode 题解工作台
从数组中移除最大值和最小值
给你一个下标从 0 开始的数组 nums ,数组由若干 互不相同 的整数组成。 nums 中有一个值最小的元素和一个值最大的元素。分别称为 最小值 和 最大值 。你的目标是从数组中移除这两个元素。 一次 删除 操作定义为从数组的 前面 移除一个元素或从数组的 后面 移除一个元素。 返回将数组中最小值…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
class Solution: def minimumDeletions(self, nums: List[int]) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个下标从 0 开始的数组 nums ,数组由若干 互不相同 的整数组成。
nums 中有一个值最小的元素和一个值最大的元素。分别称为 最小值 和 最大值 。你的目标是从数组中移除这两个元素。
一次 删除 操作定义为从数组的 前面 移除一个元素或从数组的 后面 移除一个元素。
返回将数组中最小值和最大值 都 移除需要的最小删除次数。
示例 1:
输入:nums = [2,10,7,5,4,1,8,6] 输出:5 解释: 数组中的最小元素是 nums[5] ,值为 1 。 数组中的最大元素是 nums[1] ,值为 10 。 将最大值和最小值都移除需要从数组前面移除 2 个元素,从数组后面移除 3 个元素。 结果是 2 + 3 = 5 ,这是所有可能情况中的最小删除次数。
示例 2:
输入:nums = [0,-4,19,1,8,-2,-3,5] 输出:3 解释: 数组中的最小元素是 nums[1] ,值为 -4 。 数组中的最大元素是 nums[2] ,值为 19 。 将最大值和最小值都移除需要从数组前面移除 3 个元素。 结果是 3 ,这是所有可能情况中的最小删除次数。
示例 3:
输入:nums = [101] 输出:1 解释: 数组中只有这一个元素,那么它既是数组中的最小值又是数组中的最大值。 移除它只需要 1 次删除操作。
提示:
1 <= nums.length <= 105-105 <= nums[i] <= 105nums中的整数 互不相同
解题思路
方法一
class Solution:
def minimumDeletions(self, nums: List[int]) -> int:
mi = mx = 0
for i, num in enumerate(nums):
if num < nums[mi]:
mi = i
if num > nums[mx]:
mx = i
if mi > mx:
mi, mx = mx, mi
return min(mx + 1, len(nums) - mi, mi + 1 + len(nums) - mx)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate shows an understanding of greedy algorithms and how they apply to array manipulation.
- question_mark
The candidate considers multiple approaches to minimize deletions and effectively handles edge cases.
- question_mark
The candidate optimizes the solution for both time and space complexity while clearly explaining their approach.
常见陷阱
外企场景- error
The candidate might overlook edge cases where the array only contains one element, or where the min and max elements are at the same position.
- error
Failing to account for the scenario where deletions must come from both ends of the array could lead to suboptimal solutions.
- error
Not validating the array’s size or handling out-of-bounds scenarios efficiently could result in runtime errors.
进阶变体
外企场景- arrow_right_alt
The problem could be modified to allow removing elements only from one side of the array (front or back).
- arrow_right_alt
An extension of this problem could involve keeping track of the deleted elements in addition to the deletions themselves.
- arrow_right_alt
A more complex variant might involve removing the minimum and maximum while ensuring the remaining elements maintain a specific order.