当前位置:   article > 正文

Golang | Leetcode Golang题解之第315题计算右侧小于当前元素的个数

Golang | Leetcode Golang题解之第315题计算右侧小于当前元素的个数

题目:

题解:

  1. var a, c []int
  2. func countSmaller(nums []int) []int {
  3. resultList := []int{}
  4. discretization(nums)
  5. c = make([]int, len(nums) + 5)
  6. for i := len(nums) - 1; i >= 0; i-- {
  7. id := getId(nums[i])
  8. resultList = append(resultList, query(id - 1))
  9. update(id)
  10. }
  11. for i := 0; i < len(resultList)/2; i++ {
  12. resultList[i], resultList[len(resultList)-1-i] = resultList[len(resultList)-1-i], resultList[i]
  13. }
  14. return resultList
  15. }
  16. func lowBit(x int) int {
  17. return x & (-x)
  18. }
  19. func update(pos int) {
  20. for pos < len(c) {
  21. c[pos]++
  22. pos += lowBit(pos)
  23. }
  24. }
  25. func query(pos int) int {
  26. ret := 0
  27. for pos > 0 {
  28. ret += c[pos]
  29. pos -= lowBit(pos)
  30. }
  31. return ret
  32. }
  33. func discretization(nums []int) {
  34. set := map[int]struct{}{}
  35. for _, num := range nums {
  36. set[num] = struct{}{}
  37. }
  38. a = make([]int, 0, len(nums))
  39. for num := range set {
  40. a = append(a, num)
  41. }
  42. sort.Ints(a)
  43. }
  44. func getId(x int) int {
  45. return sort.SearchInts(a, x) + 1
  46. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/926501
推荐阅读
相关标签
  

闽ICP备14008679号