微软 SDE 真实高频面试题:如何根据城市人口权重随机生成城市名称?

25次阅读
没有评论
// City Generator
// Given a list of city names and their corresponding populations, write a function to output a
// random city name subject to the following constraint: the probability of the function to output a
// city's name is based on its population divided by the sum of all cities' population.

// For example:
// NY: 7MM
// SF: 5MM
// LA: 8MM

// The probability to generate NY is 7/20, SF is 1/4.

这题是微软常考的“加权随机抽样(Weighted Random Selection)”。给城市及其人口,返回城市名称,概率按人口占比决定。常用方法是前缀和数组+二分搜索,也考察对概率分布与随机数生成的理解。

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0