315 Count of Smaller Numbers After Self
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].Naive Implementation
class Solution:
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def next_smallest_element(nums):
stack = []
next_smallest = [-1] * len(nums)
for i, num in enumerate(nums, 0):
while stack and stack[-1][1] > num:
next_smallest[stack[-1][0]] = i
stack.pop()
stack.append((i, num))
return next_smallest
def count_num_smallested(start, ref):
count = 0
for i in range(start, len(nums)):
if nums[i] < ref:
count += 1
return count
next_smallest = next_smallest_element(nums)
count_smaller = [0] * len(nums)
for i in range(len(nums) - 2, -1, -1):
if next_smallest[i] != -1:
count_smaller[i] = count_num_smallested(next_smallest[i], nums[i])
return count_smallerLast updated