原題
對(duì)于一個(gè)數(shù)組确憨,我們可以對(duì)其建立一棵線段樹(shù), 每個(gè)結(jié)點(diǎn)存儲(chǔ)一個(gè)額外的值count來(lái)代表這個(gè)結(jié)點(diǎn)所指代的數(shù)組區(qū)間內(nèi)的元素個(gè)數(shù). (數(shù)組中并不一定每個(gè)位置上都有元素)
實(shí)現(xiàn)一個(gè)query的方法,該方法接受三個(gè)參數(shù)root, start和end, 分別代表線段樹(shù)的根節(jié)點(diǎn)和需要查詢(xún)的區(qū)間龄坪,找到數(shù)組中在區(qū)間[start, end]內(nèi)的元素個(gè)數(shù)腾窝。
對(duì)于數(shù)組 [0, 2, 3], 對(duì)應(yīng)的線段樹(shù)為:
[0, 3, count=3]
/ \
[0,1,count=1] [2,3,count=2]
/ \ / \
[0,0,count=1] [1,1,count=0] [2,2,count=1], [3,3,count=1]
query(1, 1), return 0
query(1, 2), return 1
query(2, 3), return 2
query(0, 2), return 2
解題思路
- 本題為值型線段樹(shù)的Query
- 如果查詢(xún)區(qū)間 == 節(jié)點(diǎn)表示區(qū)間 => 直接返回root.count
- 如果查詢(xún)區(qū)間被節(jié)點(diǎn)表示的左/右區(qū)間包含 => 遞歸搜索左/右區(qū)間
- 如果查詢(xún)區(qū)間和結(jié)點(diǎn)表示的區(qū)間相交不相等 => 分裂遞歸搜索左/右區(qū)間
- 典型的divide & conquer
- 最后返回 leftCount + rightCount
完整代碼
"""
Definition of SegmentTreeNode:
class SegmentTreeNode:
def __init__(self, start, end, count):
self.start, self.end, self.count = start, end, count
self.left, self.right = None, None
"""
class Solution:
# @param root, start, end: The root of segment tree and
# an segment / interval
# @return: The count number in the interval [start, end]
def query(self, root, start, end):
if start > end or root == None:
return 0
if root.start >= start and root.end <= end:
return root.count
mid = root.start + (root.end - root.start) / 2
leftCount, rightCount = 0, 0
if start <= mid:
if mid < end:
leftCount = self.query(root.left, start, mid)
else:
leftCount = self.query(root.left, start, end)
if mid < end:
if start <= mid:
rightCount = self.query(root.right, mid + 1, end)
else:
rightCount = self.query(root.right, start, end)
return leftCount + rightCount