

leetcode 315. 计算右侧小于当前元素的个数
source link: https://iamxcb.com/leetcode-315.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

leetcode 315. 计算右侧小于当前元素的个数
给定一个整数数组 nums,按要求返回一个新数组 counts。数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。
示例:
输入: [5,2,6,1]
输出: [2,1,1,0]
解释:
5 的右侧有 2 个更小的元素 (2 和 1).
2 的右侧仅有 1 个更小的元素 (1).
6 的右侧有 1 个更小的元素 (1).
1 的右侧有 0 个更小的元素.
从后往前遍历 nums
,构建二叉搜索树,每个节点要记录其左子树节点的个数 Count
示例代码(go)
type Node struct {
Left *Node
Right *Node
Val int
Count int
}
func countSmaller(nums []int) []int {
var root *Node
n := len(nums)
res := make([]int, n)
for i := n-1; i >= 0; i-- {
root = insert(root, nums[i], i, res)
}
return res
}
func insert(root *Node, val, index int, res []int) *Node {
if root == nil {
root = &Node{nil, nil, val, 0}
} else if val <= root.Val {
root.Count++
root.Left = insert(root.Left, val, index, res)
} else {
res[index] += root.Count + 1
root.Right = insert(root.Right, val, index, res)
}
return root
}
Recommend
-
17
【LeetCode每日一题】222.完全二叉树的节点个数.md 发表于...
-
8
KuangjuX(狂且)LeetCode-1004-最大连续1的个数IIICreated2021-02-19|Updated2021-02-20|技术 Post View:4...
-
9
191.位 1 的个数-五分钟学算法 当前位置:五分钟学算法 > LeetCodeAnimation > LeetCode 图解 | 191.位 1 的个数 ...
-
6
LeetCode 第 191 号问题:位 1 的个数-程序员小吴 当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 第 191 号问题:位 1 的个数 ...
-
7
如何隐藏input type=number元素,右侧的上下箭头时间: 10/30/2019作者: ll浏览量: 797移动端开发时,经常会用 input=tel代替input=number来调用数字键盘 。 如验证码时,我们可以用type=tel调用拨...
-
3
求小于等于n且与n互质的数的个数互质穷举法互质:两个数互质代表两者最大公约数为1最大公约数求法:辗转相除法,最小公倍数:较大值除以最大公约数乘以较小值辗转相除法:较大的数a取模较小的数b,得...
-
8
[每天一道LeetCode] 面试题40. 最小的k个数 输入整数数组 arr ,找出其中最小的 k 个数。例如,输...
-
5
一、前言🔥👨🎓作者:bug菌✏️博客: CSDN、 掘金等💌公众号:
-
2
给你一个数组 arr ,请你将每个元素用它右边最大的元素替换,如果是最后一个元素,用 -1 替换。 完成所有替换操作后,请你返回这个数组。 输入:arr = [17,18,5,4,6,1] 输出:[18,6,6,6,1,-1]
-
3
计算左侧和右侧至少大于K个元素的元素 要计算左侧和右侧至少大于K个元素的元素,您可以使用以下...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK