数字流的秩

题目链接

数字流的秩

题目描述

注意点

  • 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);
 */

关键点

  • 构建二叉搜索树的过程
相关推荐
魂梦翩跹如雨2 分钟前
数据库的“契约” —— 约束(Constrains)
java·数据库·mysql
white-persist19 分钟前
【vulhub shiro 漏洞复现】vulhub shiro CVE-2016-4437 Shiro反序列化漏洞复现详细分析解释
运维·服务器·网络·python·算法·安全·web安全
独自破碎E28 分钟前
面试官:你有用过Java的流式吗?比如说一个列表.stream这种,然后以流式去处理数据。
java·开发语言
2601_9498180943 分钟前
头歌答案--爬虫实战
java·前端·爬虫
FL16238631291 小时前
基于C#winform部署软前景分割DAViD算法的onnx模型实现前景分割
开发语言·算法·c#
2601_949817921 小时前
大厂Java进阶面试解析笔记文档
java·笔记·面试
郭wes代码1 小时前
大三Java课设:一行行敲出来的贪吃蛇,老师以为我是CV的
java·开发语言
baizhigangqw1 小时前
启发式算法WebApp实验室:从搜索策略到群体智能的能力进阶
算法·启发式算法·web app
IGAn CTOU1 小时前
王炸级更新!Spring Boot 3.4 正式发布,新特性真香!
java·spring boot·后端
C雨后彩虹2 小时前
最多等和不相交连续子序列
java·数据结构·算法·华为·面试