题目:

链接:https://leetcode-cn.com/problems/count-of-smaller-numbers-after-self

  1. 给定一个整数数组 nums,按要求返回一个新数组 counts
  2. 数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
  3. 示例:
  4. 输入:[5,2,6,1]
  5. 输出:[2,1,1,0]
  6. 解释:
  7. 5 的右侧有 2 个更小的元素 (2 1)
  8. 2 的右侧仅有 1 个更小的元素 (1)
  9. 6 的右侧有 1 个更小的元素 (1)
  10. 1 的右侧有 0 个更小的元素

答案:

时间:

5min,因为知道两分查找了。

  1. class Solution:
  2. def countSmaller(self, nums: List[int]) -> List[int]:
  3. a=[]
  4. ans=[]
  5. for num in nums[::-1]:
  6. count = bisect.bisect_left(a,num)
  7. a.insert(count,num)
  8. ans.append(count)
  9. return ans[::-1]

要点:

1. 维护右边排序即可。

倒序遍历

其他:

代码报错:无

QQ图片20200807021903.png