- Leetcode 3634. Minimum Removals to Balance Array
- 1. 解题思路
- 2. 代码实现
- 题目链接:3634. Minimum Removals to Balance Array
1. 解题思路
这一题思路上就是一个滑动窗口的思路。
我们首先将整个数组有序排列,然后分别从左向右考察每一个元素作为初始元素时,其右侧边界的位置,其两侧丢弃的元素即为要删除的元素,遍历一轮数组然后取出最小值即为最终的答案。
2. 代码实现
给出python代码实现如下:
class Solution:def minRemoval(self, nums: List[int], k: int) -> int:nums = sorted(nums)n = len(nums)l, r = 0, 0ans = nwhile r < n:limit = nums[l] * kwhile r < n and nums[r] <= limit:r += 1ans = min(ans, n-r+l)l += 1return ans
提交代码评测得到:耗时115ms,占用内存29.16MB。