LeetCode 题解工作台
水果成篮 II
给你两个长度为 n 的整数数组, fruits 和 baskets ,其中 fruits[i] 表示第 i 种水果的 数量 , baskets[j] 表示第 j 个篮子的 容量 。 你需要对 fruits 数组从左到右按照以下规则放置水果: 每种水果必须放入第一个 容量大于等于 该水果数量的 最左侧…
5
题型
5
代码语言
3
相关题
当前训练重点
简单 · 二分·搜索·答案·空间
答案摘要
我们用一个长度为 的布尔数组 记录已经被使用的篮子,用一个答案变量 记录所有未被放置的水果,初始时 $\textit{ans} = n$。 接下来,我们遍历每一种水果 ,对于当前水果,我们遍历所有的篮子,找出第一个未被使用,且容量大于等于 的篮子 。如果找到了,那么答案 减 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你两个长度为 n 的整数数组,fruits 和 baskets,其中 fruits[i] 表示第 i 种水果的 数量,baskets[j] 表示第 j 个篮子的 容量。
你需要对 fruits 数组从左到右按照以下规则放置水果:
- 每种水果必须放入第一个 容量大于等于 该水果数量的 最左侧可用篮子 中。
- 每个篮子只能装 一种 水果。
- 如果一种水果 无法放入 任何篮子,它将保持 未放置。
返回所有可能分配完成后,剩余未放置的水果种类的数量。
示例 1
输入: fruits = [4,2,5], baskets = [3,5,4]
输出: 1
解释:
fruits[0] = 4放入baskets[1] = 5。fruits[1] = 2放入baskets[0] = 3。fruits[2] = 5无法放入baskets[2] = 4。
由于有一种水果未放置,我们返回 1。
示例 2
输入: fruits = [3,6,1], baskets = [6,4,7]
输出: 0
解释:
fruits[0] = 3放入baskets[0] = 6。fruits[1] = 6无法放入baskets[1] = 4(容量不足),但可以放入下一个可用的篮子baskets[2] = 7。fruits[2] = 1放入baskets[1] = 4。
由于所有水果都已成功放置,我们返回 0。
提示:
n == fruits.length == baskets.length1 <= n <= 1001 <= fruits[i], baskets[i] <= 1000
解题思路
方法一:模拟
我们用一个长度为 的布尔数组 记录已经被使用的篮子,用一个答案变量 记录所有未被放置的水果,初始时 。
接下来,我们遍历每一种水果 ,对于当前水果,我们遍历所有的篮子,找出第一个未被使用,且容量大于等于 的篮子 。如果找到了,那么答案 减 。
遍历结束后,返回答案即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
n = len(fruits)
vis = [False] * n
ans = n
for x in fruits:
for i, y in enumerate(baskets):
if y >= x and not vis[i]:
vis[i] = True
ans -= 1
break
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n^2) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Can the candidate explain how binary search helps in narrowing down the valid answer space?
- question_mark
Does the candidate simulate the allocation process clearly and efficiently?
- question_mark
Is the candidate aware of optimizations like early stopping to avoid unnecessary checks?
常见陷阱
外企场景- error
Misunderstanding the problem statement and returning the wrong number of unplaced fruits.
- error
Overcomplicating the binary search logic without focusing on the correct range.
- error
Failing to optimize the simulation step, leading to excessive computation time.
进阶变体
外企场景- arrow_right_alt
What if the number of baskets exceeds the number of fruit types? How does the solution scale?
- arrow_right_alt
Can this problem be adapted to handle varying basket types or additional constraints?
- arrow_right_alt
How would the solution change if we needed to track which fruits were unplaced, instead of just counting them?