当前位置:网站首页>Leetcode: calculate the number of elements less than the current element on the right (sortedlist+bisect\u left)

Leetcode: calculate the number of elements less than the current element on the right (sortedlist+bisect\u left)

2022-06-24 22:36:00 Review of the white speed Dragon King

 Insert picture description here Ideas :
Look in the opposite direction
use sortedlist Add , then bisectleft Find something smaller than yourself

src:

from sortedcontainers import SortedList

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        n = len(nums)
        s = SortedList()
        ans = [0] * n

        #  Reverse traversal 
        for i in range(n - 1, -1, -1):
            #  Find something smaller than your right 
            less = s.bisect_left(nums[i])
            #  Put it in the answer 
            ans[i] = less
            #  Add yourself 
            s.add(nums[i])
        
        return ans

summary :
sortedlist + bisectleft The combination of

原网站

版权声明
本文为[Review of the white speed Dragon King]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211232152066.html