LeetCode - 3479. Fruits Into Baskets III

Medium
這題 Segment Tree 竟然才 Medium,太狠了
3479. Fruits Into Baskets IIIProblem
You are given two arrays: fruits
and baskets
, both of length n
.fruits[i]
represents the number of fruits of type i
, and baskets[j]
is the capacity of basket j
.
Starting from the left, you place fruits into baskets according to the following rules:
- Each fruit type must be placed into the leftmost unused basket whose capacity is ≥ the number of fruits.
- Each basket can hold only one type of fruit.
- If a fruit type cannot be placed in any basket, it is considered unplaced.
Return the number of fruit types that cannot be placed in any basket.
Example 1
Input:fruits = [4, 2, 5]
, baskets = [3, 5, 4]
Output:1
Explanation:
- Fruit 4 → goes into
basket[1] = 5
- Fruit 2 → goes into
basket[0] = 3
- Fruit 5 → cannot be placed
Example 2
Input:fruits = [3, 6, 1]
, baskets = [6, 4, 7]
Output:0
Explanation:
- 3 → basket[0] = 6
- 6 → basket[2] = 7
- 1 → basket[1] = 4
All fruits are placed successfully.
Constraints
n == fruits.length == baskets.length
1 <= n <= 10^5
1 <= fruits[i], baskets[i] <= 10^9
解題思路
這題其實就是 「每種水果都想找一個最左邊還可以放得下的籃子」
用暴力一個一個檢查的話,n 上限 10^5,必 TLE
所以這題要用 Segment Tree + Binary Search
Initial Segment Tree
- 樹上儲存每個區間裡能放進的最大籃容量
max
- 建 segment tree 的空間大概會是 input 長度的 4 倍,所以設
segTree_size = 4 * n + 5
- 樹上儲存每個區間裡能放進的最大籃容量
Build Segment Tree
build_segment_tree(now, left, right)
:left == right
→ 葉節點就是baskets[left]
- mid 拆兩邊建,最後
parent = max(left child, right child)
Search leftmost_basket
用 Binary Search + Segment Tree:- 對每個 fruit i,設定
left = 0, right = n - 1, leftmost_basket = -1
- mid = (left+right)/2,如果 query (0 ~ mid) 的區間 max ≥ fruit,就代表左邊有人能放,那就把 leftmost 定 mid,但繼續往左找;不然 left = mid+1
- 對這段 range 用 Segment Tree 做 query,複雜度是 O(log n)
- 對每個 fruit i,設定
update used basket in Segment Tree
如果找到就update_segment_tree(now, left, right, position, INT_MIN)
,意思就是把這格設超小,之後查不到它,像被用過了Time & Space Complexity
- Time:建樹 O(n),每次 Binary Search O(log n) + 每次查詢/更新 segtree O(log n),總共 fruits 有 n 顆 → O(n log n)
- Space:Segment Tree 用 O(n) 空間
因為註解是邊解邊寫的,我覺得我註解寫的比較容易理解,也可以直接看註解去理解這題 XD
C++ Solution
1 | class Solution { |