数字流的秩

题目链接

数字流的秩

题目描述

注意点

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

关键点

  • 构建二叉搜索树的过程
相关推荐
数据分析螺丝钉几秒前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
no_play_no_games几秒前
「3.3」虫洞 Wormholes
数据结构·c++·算法·图论
￴ㅤ￴￴ㅤ9527超级帅1 分钟前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
五味香1 分钟前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理
无理 Java6 分钟前
【技术详解】SpringMVC框架全面解析:从入门到精通(SpringMVC)
java·后端·spring·面试·mvc·框架·springmvc
PYSpring23 分钟前
数据结构-LRU缓存(C语言实现)
c语言·数据结构·缓存
毕小宝25 分钟前
逻辑回归(下): Sigmoid 函数的发展历史
算法·机器学习·逻辑回归
小叮当爱咖啡30 分钟前
DenseNet算法:口腔癌识别
算法
希望有朝一日能如愿以偿34 分钟前
算法(食物链)
算法
gobeyye34 分钟前
spring loC&DI 详解
java·spring·rpc