数字流的秩

题目链接

数字流的秩

题目描述

注意点

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

关键点

  • 构建二叉搜索树的过程
相关推荐
WaitWaitWait013 小时前
LeetCode每日一题4.20
算法·leetcode
蒟蒻小袁3 小时前
力扣面试150题--有效的括号和简化路径
算法·leetcode·面试
不当菜虚困4 小时前
JAVA设计模式——(二)组合模式
java·设计模式·组合模式
跳跳糖炒酸奶4 小时前
第十五讲、Isaaclab中在机器人上添加传感器
人工智能·python·算法·ubuntu·机器人
jack_xu5 小时前
经典大厂面试题——缓存穿透、缓存击穿、缓存雪崩
java·redis·后端
CHQIUU6 小时前
Java 设计模式心法之第4篇 - 单例 (Singleton) 的正确打开方式与避坑指南
java·单例模式·设计模式
碎梦归途6 小时前
23种设计模式-结构型模式之享元模式(Java版本)
java·开发语言·jvm·设计模式·享元模式
明月看潮生6 小时前
青少年编程与数学 02-018 C++数据结构与算法 06课题、树
数据结构·c++·算法·青少年编程·编程与数学
小指纹6 小时前
动态规划(一)【背包】
c++·算法·动态规划
_安晓6 小时前
数据结构 -- 图的应用(一)
数据结构·算法·图论