Created
January 8, 2018 05:22
-
-
Save jianminchen/e10e35896c20628a8136393b3fc2a5e9 to your computer and use it in GitHub Desktop.
Leetcode 315 - count of smaller number - study python code, please study the discussion first
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#https://discuss.leetcode.com/topic/31405/9ms-short-java-bst-solution-get-answer-when-building-bst/2 | |
class TreeNode(object): | |
def __init__(self, x, count): | |
self.val = x | |
self.count = count # the number of points in left bottom | |
self.dup = 1 | |
self.left = None | |
self.right = None | |
class Solution(object): | |
def countSmaller(self, nums): | |
""" | |
:type nums: List[int] | |
:rtype: List[int] | |
""" | |
length = len(nums) | |
self.result = [0] * length | |
node = None | |
for i in range(length-1,-1,-1): | |
node = self.insert(node,nums[i],0,i) | |
return self.result | |
def insert(self,node,value,count,position): | |
if node is None: | |
node = TreeNode(value,0) | |
self.result[position] = count | |
elif value == node.val: | |
node.dup += 1 | |
self.result[position] = count + node.count | |
elif value > node.val: | |
node.right = self.insert(node.right,value,count+node.count+node.dup,position) | |
else: | |
node.count += 1 | |
node.left = self.insert(node.left,value,count,position) | |
return node |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment