Given a list of city names and their corresponding populations, write a program to output a city name
subject to the following constraint: the probability of the program to output a city's name is based on
its population divided by the sum of all cities' population. Assume the program will be repeatedly called many times.
For example:
NY: 7M
SF: 5M
LA: 8M
The probability to generate NY is 7/20, SF is 5/20 and LA 8/20.
这题是典型的加权随机抽样,需要先根据人口构建前缀和数组,然后通过随机数落点区间来决定最终城市。这样在多次查询时能保证输出概率精确符合人口比例。重点是前缀和结构 + 二分查找,使每次调用都能在 O(log n) 或 O(1) 时间内返回结果。
given a binary search tree, and a integer target, return the node whose value is closest to the target
BST 的结构允许我们沿着 root 往下走时不断逼近目标值:若当前节点值大于目标就往左,小于目标就往右,同时实时维护与 target 的最小差值。最终得到的就是整棵树中最接近目标值的节点。核心是利用 BST 单调分支的特性,使搜索路径天然是最优路线。
VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Meta、Google、Amazon 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Stripe 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。
正文完