class SegmentTreeNode(object):
def __init__(self,val,start,end):
self.val=val
self.start=start
self.end=end
self.children=[]
class SegmentTree(object):
def __init__(self,n):
self.root=self.build(0,n-1)
def build(self,start,end):
if start>end:
return
root=SegmentTreeNode(0,start,end)
if start==end:
return root
mid=start+end >>1
root.children=filter(None,[self.build(start,end) for start,end in ((start,mid),(mid+1,end))])
return root
def update(self,i,val,root=None):
root=root or self.root
if i<root.start or i>root.end:
return root.val
if i==root.start==root.end:
root.val+=val
return root.val
root.val=sum([self.update(i,val,c) for c in root.children])
return root.val
def sum(self,start,end,root=None):
root=root or self.root
if end<root.start or start>root.end:
return 0
if start<=root.start and end>=root.end:
return root.val
return sum([self.sum(start,end,c) for c in root.children])
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
hash_table={v:i for i,v in enumerate(sorted(set(nums)))}
tree=SegmentTree(len(hash_table))
res=[]
#start calculate from the right most element
for i in range(len(nums)-1,-1,-1):
#get the sum of the occurances of all numbers smaller than nums[i]
res.append(tree.sum(0,hash_table[nums[i]]-1))
#add the occurance of nums[i] to the tree
tree.update(hash_table[nums[i]],1)
return res[::-1]
315. Count of Smaller Numbers After Self
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 問(wèn)題描述 You are given an integer array nums and you have to ...
- You are given an integer array nums and you have to retur...
- You are given an integer array nums and you have to retu...
- My code: reference:https://discuss.leetcode.com/topic/314...
- 城市里的掙扎與拼搏,讓我麻木著自己的生活,我離開(kāi)了母親的雙手,開(kāi)始自己掌握我的生活,我把她,留在了故鄉(xiāng),我把情,藏...