halfrost
January 15, 2020
560

# Segment Tree Basics

January 15, 2020

## Transcript

2. ### Range Minimum/Maximum Query •需求：在饿了么的⼀个⽤户的历史订单中，找出该⽤户指定⼀段 时间内单笔订单最贵/最便宜的订单 One problem •O(n), when query

K —> ∞ times ?
3. ### Range Minimum/Maximum Query •需求：在饿了么的⼀个⽤户的历史订单中，求出找出该⽤户指定 ⼀段时间内累积消费总⾦额 Another problem •O(n), when query

K —> ∞ times ? •preﬁxSum, time O(n), query O(1)
4. ### Range Minimum/Maximum Query •需求：在 12306 ⽹站上，统计⼀条线路上任意指定两个站点之间 的可售出的票数总和 One more thing

•O(n), when query K —> ∞ times ? •preﬁxSum, time O(n), update O(n), query O(1)

O(1) ？
6. ### Presentation agenda 6 What How to use Leetcode example What

is segment tree 2 3 1 How Example
7. ### Deﬁne Segment Tree 7 1. ❌ Complete Binary Tree 2.

∈ Balanced Binary Tree 3. As Full binary tree
8. ### How many node Segment Tree 8 0-level ： 1 1-level

： 2 2-level ： 4 3-level ： 8 4-level ： 16 (n-1)—level ：2^(n-1) n-level：2^n Σ 0-(n-1) level：Σ = 2^n - 1 ≈ n-level => 2n Mathematical Induction：Σ = 4n (n = 2^k or n = 2^k + 1)
9. ### How many node Segment Tree 9 •When n≥3, [1,n] segment

split [1,n] into 2*⌊log (n-1)⌋ sub- Interval •4n ≥ 2*⌊log (n-1)⌋ <= 2n ≥ log (n-1) <= 4^n ≥ n-1

O(n)

n)

19. ### Compared ST VS Array 19 20% 80% 60% 40% 2585

785 Update: Array O(n) | Segment Tree O(log n) Query: Array O(n) | Segment Tree O(log n)

25. ### Segment Tree 25 Example •judge threshold •count = map[1:[0 1

4 5] 2:[2 3]] •eg: 1 in [0,5] count , twice binary search, ﬁnd [lowerBound， upperBound) •(upperBound - lowerBound) ≥ threshold
26. ### Segment Tree 26 •Leetcode 327. Count of Range Sum •Leetcode

715. Range Module •Leetcode 699. Falling Squares & 732. My Calendar III •Leetcode 850. Rectangle Area II •Leetcode 218. The Skyline Problem Exercise
27. ### Advance 27 15% 35% 50% •One point update (update: min/change,

query: sum/min) •Interval update (update: min/change, query: sum/hash) •Discretization •Interval merge •Scan line •Binary Index Tree