数字流的秩

题目链接

数字流的秩

题目描述

注意点

  • x <= 50000

解答思路

  • 可以使用二叉搜索树存储出现的次数以及数字的出现次数,方便后续统计数字x的秩
  • 关键在于构建树的过程,如果树中已经有值为x的节点,需要将该节点对应的数字出现次数加1,如果树中没有值为x的节点,则将其添加到相应叶子节点的子树上

代码

java 复制代码
class StreamRank {
    TreeNode root;

    public StreamRank() {
        root = null;
    }
    
    public void track(int x) {
        if (root == null) {
            root = new TreeNode();
            root.val = x;
            root.num = 1;
            return;
        }
        // 找到值为x的节点,没找到x则需要找到x应该插入的节点位置
        TreeNode node = findX(x, root);
        // 找到了值为x的节点
        if (node.val == x) {
            node.num += 1;
            return;
        }
        // 没有找到需要将值为x的新节点插入到树中
        TreeNode newNode = new TreeNode();
        newNode.val = x;
        newNode.num = 1;
        if (node.val > x) {
            node.left = newNode;
        } else {
            node.right = newNode;
        }
    }
    
    public int getRankOfNumber(int x) {
        return countNumber(x, root);
    }

    public TreeNode findX(int x, TreeNode node) {
        if (node.val == x) {
            return node;
        }
        if (node.val > x) {
            if (node.left == null) {
                return node;
            }
            return findX(x, node.left);
        } else {
            if (node.right == null) {
                return node;
            }
            return findX(x, node.right);
        }
    }

    public int countNumber(int x, TreeNode node) {
        if (node == null) {
            return 0;
        }
        // 左子树更有可能小于等于x
        int sum = countNumber(x, node.left);
        if (node.val <= x) {
            sum = sum + node.num + countNumber(x, node.right);
        }
        return sum;
    }
}

class TreeNode {
    TreeNode left;
    TreeNode right;
    int val;
    int num;
}

/**
 * Your StreamRank object will be instantiated and called as such:
 * StreamRank obj = new StreamRank();
 * obj.track(x);
 * int param_2 = obj.getRankOfNumber(x);
 */

关键点

  • 构建二叉搜索树的过程
相关推荐
一缕茶香思绪万堵10 分钟前
028.爬虫专用浏览器-抓取#shadowRoot(closed)下
java·后端
Deamon Tree16 分钟前
如何保证缓存与数据库更新时候的一致性
java·数据库·缓存
9号达人18 分钟前
认证方案的设计与思考
java·后端·面试
大G的笔记本25 分钟前
MySQL 中的 行锁(Record Lock) 和 间隙锁(Gap Lock)
java·数据库·mysql
R.lin26 分钟前
Java支付对接策略模式详细设计
java·架构·策略模式
没有bug.的程序员27 分钟前
Spring Boot 常见性能与配置优化
java·spring boot·后端·spring·动态代理
没有bug.的程序员31 分钟前
Spring Boot Actuator 监控机制解析
java·前端·spring boot·spring·源码
三次拒绝王俊凯31 分钟前
java求职学习day47
java·开发语言·学习
包饭厅咸鱼1 小时前
autojs----2025淘宝淘金币跳一跳自动化
java·javascript·自动化
MicroTech20251 小时前
MLGO微算法科技发布多用户协同推理批处理优化系统,重构AI推理服务效率与能耗新标准
人工智能·科技·算法