Interview Questions: Balanced Search Trees

Google算法题:132模式 题目 Given a sequence of n integers a1, a2, ..., an, a 132pattern is a subsequence ai, aj, ak such that i j kand ai ak aj. Design an algorithm that takes a list of n numbers as input and 阅读详情

Balanced Search Trees

Red–black BST with no extra memory. Describe how to save the memory for storing the color information when implementing a red–black BST.

Hint: modify the structure of the BST to encode the color information.

BST需要满足 左结点L < 根结点P < 右结点R,那么这样设定:如果 L > P,那么说明L为红结点;如果 R < P,那么说明R为红结点。因此在左偏红黑树中,将一个结点标记为红色的方法是:将结点red的值变为 red.value=2∗parent−red.valuered.value=2*parent-red.valuered.value=2∗parent−red.value。

public class LLRB {
    private static final int LEFT = 1;
    private static final int RIGHT = 2;
    private Node root;

    public boolean search(int target) {
        Node x = root;
        int preValue = x.val;
        int flag = 0;
        while (x != null) {
            int trueValue = x.val;
            if (flag == LEFT && trueValue > preValue) {
                trueValue = 2 * preValue - trueValue;
            }
            if (target < trueValue) {
                x = x.left;
                flag = LEFT;
                preValue = trueValue;
            } else if (target > trueValue) {
                x = x.right;
            } else {
                return true;
            }
        }

        return false;
    }

    public void insert(int val) {
        insert(root, val, 0, 0);
        root.val = -1 * root.val;
    }

    private Node insert(Node x, int val, int preValue, int flag) {
        if (x == null) {
            return new Node(2 * preValue - val);
        }
        int trueValue = x.val;
        if (flag == LEFT && trueValue > preValue) {
            trueValue = 2 * preValue - trueValue;
        }
        if (val < trueValue) {
            x.left = insert(x.left, val, trueValue, LEFT);
        } else if (val > trueValue) {
            x.right = insert(x.right, val, trueValue, RIGHT);
        }

        if ((x.right != null && x.right.val > trueValue) && (x.left == null || x.left.val < trueValue)) {
            x = rotateLeft(x, trueValue, trueValue != x.val);
        }
        if (x.left != null && x.left.left != null && x.left.val > trueValue
                && x.left.left.val > (2 * (2 * trueValue - x.left.val) - x.left.left.val)) {
            x = rotateRight(x, trueValue, trueValue != x.val);
        }
        if ((x.left != null && x.left.val > trueValue) && (x.right != null && x.right.val < trueValue)) {
            flipColors(x, trueValue);
        }

        return x;
    }

    private Node rotateLeft(Node x, int preValue, boolean isRed) {
        Node y = x.right;

        if (isRed) {
            x.val = 2 * preValue - x.val;
        }
        y.val = 2 * x.val - y.val;

        x.right = y.left;
        y.left = x;
        x.val = 2 * y.val - x.val;
        if (isRed) {
            y.val = 2 * preValue - y.val;
        }

        return y;
    }

    private Node rotateRight(Node x, int preValue, boolean isRed) {
        Node y = x.left;

        if (isRed) {
            x.val = 2 * preValue - x.val;
        }
        y.val = 2 * x.val - y.val;

        x.left = y.right;
        y.right = x;
        x.val = 2 * y.val - x.val;
        if (isRed) {
            y.val = 2 * preValue - y.val;
        }

        return y;
    }

    private void flipColors(Node x, int preValue) {
        x.left.val = 2 * x.val - x.left.val;
        x.right.val = 2 * x.val - x.right.val;
        x.val = 2 * preValue - x.val;
    }

    private class Node {
        Node left, right;
        int val;

        Node(int val) {
            this.val = val;
        }
    }
}

Document search. Design an algorithm that takes a sequence of n document words and a sequence of m query words and find the shortest interval in which the m query words appear in the document in the order given. The length of an interval is the number of words in that interval.

Hint: for each word, maintain a sorted list of the indices in the document in which that word appears. Scan through the sorted lists of the query words in a judicious manner.

题目大意:给定一组n个被查找单词,和一组m个待查找单词,要求在n个被查找单词中找到一个最小区间,使得这个区间包含所有m个待查找单词,且这m个单词出现的顺序和给定的顺序一致。

解法:给每一个不同的单词开一个列表,记录该单词在n个被查找单词中出现的下标位置(有序);得到m个待查找单词对应的位置列表,从这m个列表中各挑出一个数字组成序列,要求该序列首尾之差最小,且要保证序列为递增序列。

import java.util.*;

public class Document {
    private String[] document;
    private String[] query;

    public void search() {
		// 记录满足条件的最短区间的两个端点
        // 将first设为-1有助于判断最终能否找到有效的区间
        int first = -1, last = document.length - 1;

        // 根据每个不同的单词生成对应的递增下标序列
        Map<String, Queue<Integer>> map = new HashMap<>();
        for (int i = 0; i < document.length; i++) {
            if (!map.containsKey(document[i])) {
                Queue<Integer> q = new LinkedList<>();
                q.add(i);
                map.put(document[i], q);
            } else {
                map.get(document[i]).add(i);
            }
        }

        // 摘出m个待查找单词对应的下标序列
        Queue<Integer>[] q = new Queue[query.length];
        for (int i = 0; i < query.length; i++) {
            q[i] = map.get(query[i]);
        }

        // 搜寻满足条件的区间
        OUTER:
        for (int i : q[0]) {
            int left = i, right = i;	// 记录当前区间的两个端点
            for (int j = 1; j < q.length; j++) {
                // 每次都选取各序列中满足条件的最小的位置,并出队小于这个位置的所有下标
                while (!q[j].isEmpty() && q[j].peek() <= right) {
                    q[j].poll();
                }
                if (q[j].isEmpty()) {
                    break OUTER;		// 当某一单词对应下标全出队后,可直接跳出外层循环
                } else {
                    right = q[j].peek();	// 更新当前区间的右端点
                }
            }
            // 更新最短区间的左右端点
            if (right - left  < last - first) {
                first = left;
                last = right;
            }
        }
        	
        if (first != -1) {
            System.out.println(last - first);
        } else {
            System.out.println("Not Found");
        }
    }
}

Generalized queue. Design a generalized queue data type that supports all of the following operations in logarithmic time (or better) in the worst case.

  • Create an empty data structure.
  • Append an item to the end of the queue.
  • Remove an item from the front of the queue.
  • Return the ithi^{th}ith item in the queue.
  • Remove the ithi^{th}ith item from the queue.

Hint: create a red–black BST where the keys are integers and the values are the items such that the ithi^{th}ith largest integer key in the red–black BST corresponds to the ithi^{th}ith item in the queue.

用红黑树构建的符号表来储存队列元素,key值记录入队序号,value值储存对应item。出队则找最小的序号,入队则加入一个新序号;找到第i大的元素,就是在树中找到序号第i大的结点,这与之前BST实现的符号表中的select()实现方法是一样的。

Interview Questions: Minimum Spanning Trees Minimum Spanning Trees Bottleneck minimum spanning tree. Given a connected edge-weighted graph, design an efficient algorithm to find a minimum bottleneck spanning tree. The bottleneck capacity of a ... 阅读详情

相关推荐

新手必看:LiteRadio 2c SE遥控器从开箱到飞行的完整指南(附常见问题解答)

本文为新手提供LiteRadio 2c SE遥控器的完整使用指南,涵盖从开箱到首飞的20个关键步骤。详细介绍了遥控器的功能设置、与无人机的对频技巧以及首飞注意事项,帮助用户快速掌握飞行控制,避免常见错误。特别适合无人机初学者阅读。

weixin_29209801的博客 379

Coursera - Algorithm (Princeton) - 习题与解答 - Week 5

Week 5 Red–black BST with No Extra Memory 问题 Describe how to save the memory for storing the color information when implementing a red–black BST. 分析 本来自信满满地认为“比特”可以解决一切,然后猛然反应过来布尔值就是比特…… 然后这个题宛如脑筋急转弯一...

支锦铭的博客 615

【讯飞星火大模型AI】SpringBoot整合星火API:从零构建智能数据分析助手

本文详细介绍了如何使用SpringBoot框架整合讯飞星火大模型API,从零构建一个智能数据分析助手。通过清晰的步骤,指导开发者完成API密钥申请、项目搭建、SDK集成与核心代码编写,实现用户通过自然语言指令和CSV数据,即可自动获得ECharts图表代码与专业数据分析结论,极大降低数据分析与可视化的门槛。

neovim7hacker的博客 275

red-black BST的理解

红黑二插搜索树是一种特殊的二插搜索树,用来表示带有两个关键字Key的三个子节点的结点。 如2-3trees结点A(关键Key为 f,m)左子结点为B(keyB<f),中间子结点为C(f<keyC<m),右边子结点为D(keyD>m),转换成红黑二插搜索树为root结点(关键Key为m),左1子结点(Key左1<m),右1子结点(Key右1>m),左1的左11子...

风之云的博客 535

Windows服务器XMRig挖矿病毒深度清除实战指南

XMRig是一种广泛用于Monero(XMR)加密货币挖矿的开源工具,其在Windows环境中的持久化机制已远超传统木马范畴,融合WMI事件订阅、服务伪装、PowerShell无文件执行与注册表隐写等多重反检测技术。理解其基于行为而非特征的生存逻辑,是实现有效检测与根除的前提。该技术具备强隐蔽性、高自愈性与网络通信合法化特征,常见于RDP弱口令爆破、SMB共享泄露及PowerShell远程执行等非漏洞类入侵场景。本文聚焦Windows原生命令与Sysinternals工具链,提供覆盖进程定位、WMI清理、服

weixin_30535843的博客 730

MATLAB 2022b 用户专属:保姆级IPOPT求解器安装配置全流程(含OPTI工具箱)

本文为MATLAB 2022b用户提供IPOPT求解器的详细安装与配置指南,涵盖OPTI工具箱的适配安装、环境变量设置及常见问题解决方案。通过实战案例演示非线性优化问题的求解过程,帮助用户高效部署这一强大的优化工具,提升工程计算效率。

weixin_29092031的博客 405

OpenCV实战之人脸美颜美型(八)——大眼(上)

从大众审美的角度来看,眼睛适当的“变大”会让人显得更加年轻。因此美型中就有一项大眼功能,其效果就是让眼睛适当变大,这章内容就围绕着大眼算法展开。

On my way 1211

普林斯顿·算法·PART I:Balanced search tree

平衡搜索树 2-3 search trees 于是先来了解下 2-3 查找树,它可以保证树的平衡性,维护树高在 lgN 级别。这里的 2,3 指的是孩子的数目 search 查找和二叉查找树一样,虽然现在有的点有两个键,但是也没有什么关系。 insert 插入操作比较关键,解释了为什么可以保证树的平衡性,下面是各种情况的示意: 插入 2-node 时,直接插入把这个节点变成 3-node 即...

qq_37356854的博客 409

多组学联合高级Mantel-test热图

对应的是「metabo」中物质间的相关性热图,单元格色块颜色表示相关系数大小,橙色表示+相关,绿色表示-相关;单元格内的数值表示相关性值大小,星号表示显著性。双组学(微生物组/ 转录组/代谢组等两两组合)关联分析,可视化组学特征间的关联显著性、强度及相关方向。表示<trans>与<metabo>中物质的Mantel test结果。表示整体相关的系数,连线颜色表示相关系数的显著性检验结果。宿主-微生物互作、疾病多组学机制、环境-生物多组学关联。为物质名称,不允许存在空值、重复值。

多组・学・多组学 360

YOLOv11缝合添加注意力机制:添加YOLO-Face的SEAM到并行通道空间注意力机制【附代码】

在目标检测的实际应用中,物体遮挡是一个严重影响检测精度的难点。本文将基于YOLOv11架构,探索融合YOLO-Face中提出的SEAM注意力机制以提升对遮挡物体的感知能力,并在此基础上提出一种轻量化双路径并行注意力机制C2PSA,进一步提升检测性能。

一键难忘的博客 1527

Balanced Search Trees

平衡搜索树 前面介绍的二叉搜索树在最坏情况下的性能还是很糟糕,而且我们不能控制操作的顺序,有时根本就不是随机的,我们希望找到有更好性能保证的算法。 2-3 search trees 于是先来了解下 2-3 查找树,它可以保证树的平衡性,维护树高在 lgN 级别。这里的 2,3 指的是孩子的数目,图例: 有两个孩子的节点和二叉搜索树一样,节点里有一个键,且大于左子树的键并小于右子树的键。...

dlei7655的博客 406

NR TA

这篇是NR TA的笔记,之前有对R17 NTN TA进行了简单总结,但是也仅仅局限在NTN部分,其他TA基本过程没有涉及,这篇是针对R16版本协议对NR TA相关内容做的总结。和PUSCH power control过程类似,NR TA也可以分为开环 和闭环调整,相关内容分散在38.300,38.211,38.213,38.321,38.133和38.331。后面就按照38.300 TA相关概念,38.211中有关TA定义,38.213 TA 相关内容,38.321 TA控制过程,38.133 Timi

ModemProtocol的博客 768

LeetCode[132] Pattern

Leetcode[132] Pattern Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design ...

weixin_34310785的博客 103

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

8 Puzzle

8 Puzzle Board.java 照着API写即可。注意每次调用twin()都要返回相同的值,即twin()只能交换两个固定位置的数字。 import edu.princeton.cs.algs4.StdRandom; import java.util.ArrayList; import java.util.List; public class Board { private f...

Mapoos 900

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Collinear Points

Collinear Points Point.java 照要求补API即可。 import java.util.Comparator; import edu.princeton.cs.algs4.StdDraw; public class Point implements Comparable<Point> { private final int x; // x-c...

Mapoos 717

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Percolation

Percolation Percolation.java 主要问题为backwash。其形成原因为:因为存在上下两个虚拟节点,当percolates()为true上下贯通时,所有在最底排的已经打开的节点都会变成与上虚拟节点连通(每打开一个底部节点,都会将其与下虚拟节点连通)。解决方法是再设置一个union-find,但只提供上虚拟节点,将isFull()放在第二个union-find中进行判断。 ...

Mapoos 685

Interview Questions: Stacks and Queues

Interview Questions: Stacks and Queues Queue with two stacks. Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations. 利用两个栈来实现队列,具体方法为:...

Mapoos 461

Interview Questions: Analysis of Algorithms

Analysis of Algorithms 3-SUM in quadratic time. Design an algorithm for the 3-SUM problem that takes time proportional to n2n^2n2 in the worst case. You may assume that you can sort the n integers in...

Mapoos 452

Interview Questions: Union-Find

Interview Questions: Union-Find Social network connectivity. Given a social network containing nn members and a log file containing mm timestamps at which times pairs of members formed friendships, d...

Mapoos 318

Deques and Randomized Queues

Deques and Randomized Queues Deque.java 双向队列,因为要求所有操作的复杂度为O(1)O(1)O(1),采用双向链表进行实现。 import java.util.Iterator; import java.util.NoSuchElementException; public class Deque<Item> implements Iterab...

Mapoos 313

Interview Questions: Priority Queues

Priority Queues Dynamic median. Design a data type that supports insert in logarithmic time, find-the-median in constant time, and remove-the-median in logarithmic time. If the number of keys in the ...

Mapoos 290

Interview Questions: Elementary Symbol Tables

Elementary Symbol Tables Java autoboxing and equals(). Consider two

Mapoos 283

Interview Questions: Hash Tables

Hash Tables 4-SUM. Given an array a[] of nn integers, the 4-SUM problem is to determine if there exist distinct indices i, j, k, and l such that a[i]+a[j]=a[k]+a[l]. Design an algorithm for the 4-SUM...

Mapoos 281

Interview Questions: Elementary Sorts

Elementary Sorts Intersection of two sets. Given two arrays

Mapoos 278
上一篇: 38. Count and Say (E)
下一篇: Kd-Trees
绿色小光头
博客等级 码龄10年 10粉丝 301原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值