★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10403265.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.

Note:

  1. 1 <= w.length <= 10000
  2. 1 <= w[i] <= 10^5
  3. pickIndex will be called at most 10000 times.

Example 1:

Input:
["Solution","pickIndex"]
[[[1]],[]]
Output: [null,0]

Example 2:

Input:
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
Output: [null,0,1,1,1,0]

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. Solution's constructor has one argument, the array wpickIndex has no arguments. Arguments are always wrapped with a list, even if there aren't any.


给定一个正整数数组 w ,其中 w[i] 代表位置 i 的权重,请写一个函数 pickIndex ,它可以随机地获取位置 i,选取位置 i 的概率与 w[i] 成正比。

说明:

  1. 1 <= w.length <= 10000
  2. 1 <= w[i] <= 10^5
  3. pickIndex 将被调用不超过 10000 次

示例1:

输入:
["Solution","pickIndex"]
[[[1]],[]]
输出: [null,0]

示例2:

输入:
["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
[[[1,3]],[],[],[],[],[]]
输出: [null,0,1,1,1,0]

输入语法说明:

输入是两个列表:调用成员函数名和调用的参数。Solution 的构造函数有一个参数,即数组 wpickIndex 没有参数。输入参数是一个列表,即使参数为空,也会输入一个 [] 空列表。


704ms

 1 class Solution {
 2     var total: Int
 3     var pTotal: [Int]
 4     init(_ w: [Int]) {
 5         total = 0
 6         pTotal = [Int]()
 7         for x in w{
 8             total += x
 9             pTotal.append(total)
10         }
11     }
12
13     func pickIndex() -> Int {
14         let index = Int.random(in: 0..<total)
15         var lo = 0, hi = pTotal.count-1
16         while lo != hi{
17             let mid = (lo+hi)/2
18             if pTotal[mid] <= index{
19                 lo = mid + 1
20             }else{
21                 hi = mid
22             }
23         }
24         return lo
25     }
26 }
27
28 /**
29  * Your Solution object will be instantiated and called as such:
30  * let obj = Solution(w)
31  * let ret_1: Int = obj.pickIndex()
32  */


720ms

 1 class Solution {
 2
 3     let nums:[Int]
 4
 5     init(_ w: [Int]) {
 6         var sum = 0
 7         var result = [Int]()
 8         w.forEach {
 9             sum += $0
10             result.append(sum)
11         }
12         nums = result
13     }
14
15     func pickIndex() -> Int {
16        let sum = nums.last!
17        let num = Int.random(in: 0..<sum) % sum
18         var left = 0
19         var right = nums.count - 1
20         while left + 1 < right {
21             let mid = left + (right - left) / 2
22             if nums[mid] > num {
23                 right = mid
24             } else {
25                 left = mid
26             }
27         }
28
29         if nums[left] > num {
30             return left
31         } else {
32             return right
33         }
34     }
35 }


752ms

 1 class Solution {
 2
 3     let w: [Int]
 4     let sum: Int
 5
 6     init(_ w: [Int]) {
 7         sum = w.reduce(0, +)
 8         self.w = w.reduce([Int]()){
 9             let n = ($0.last ?? 0) + $1
10             return $0 + [n]
11         }
12     }
13
14     func pickIndex() -> Int {
15         let random = Int.random(in: 0...sum-1)
16         return searchInsert(w, random)
17     }
18
19     func searchInsert(_ nums: [Int], _ target: Int) -> Int {
20         var low = 0
21         var high = nums.count-1
22         while low <= high {
23             let middle = (low + high) / 2
24             if nums[middle] == target {
25                 return middle+1
26             } else if nums[middle] > target {
27                 high = middle - 1
28             } else {
29                 low = middle + 1
30             }
31         }
32         return low
33     }
34 }


772ms

 1 class Solution {
 2
 3     var sum: [Int]
 4
 5     init(_ w: [Int]) {
 6         sum = [Int]()
 7         sum.append(w[0])
 8         for i in 1..<w.count {
 9             sum.append(sum[i-1] + w[i])
10         }
11     }
12
13     func pickIndex() -> Int {
14         let value = Int.random(in: 1...sum.last!)
15         return bSearch(value, 0, sum.count - 1)
16     }
17
18     private func bSearch(_ value: Int, _ start: Int, _ end: Int) -> Int {
19         let mid = start + (end - start) / 2
20         if sum[mid] >= value && (start == mid || sum[mid - 1] < value) { return mid }
21         if sum[mid] < value {
22             return bSearch(value, mid + 1, end)
23         }
24         return bSearch(value, start, mid - 1)
25     }
26 }


784ms

 1 class Solution {
 2
 3     private let accSum: [Int]
 4
 5     init(_ w: [Int]) {
 6         self.accSum = w.reduce([]) { $0 + [($0.last ?? 0) + $1]}
 7     }
 8
 9     func pickIndex() -> Int {
10         let num = Int.random(in: 1 ... accSum.last!)
11         var (left, right) = (0, accSum.count - 1)
12         while left < right {
13             let mid = left + (right - left) / 2
14             if accSum[mid] == num {
15                 return mid
16             } else if accSum[mid] < num {
17                 left = mid + 1
18             } else {
19                 right = mid
20             }
21         }
22
23         return left
24     }
25 }


Runtime: 976 ms
Memory Usage: 19.9 MB
 1 class Solution {
 2     var sum:[Int]
 3
 4     init(_ w: [Int]) {
 5         sum = w
 6         for i in 1..<w.count
 7         {
 8             sum[i] += sum[i - 1]
 9         }
10     }
11
12     func pickIndex() -> Int {
13         var x:Int = Int.random(in:0..<sum.last!)
14         var left:Int = 0
15         var right:Int = sum.count - 1
16         var mid:Int = 0
17         while (left < right)
18         {
19             mid = left + (right - left) / 2
20             if sum[mid] <= x
21             {
22                 left = mid + 1
23             }
24             else
25             {
26                 right = mid
27             }
28         }
29         return right
30     }
31 }
32
33 /**
34  * Your Solution object will be instantiated and called as such:
35  * let obj = Solution(w)
36  * let ret_1: Int = obj.pickIndex()
37  */
38  

转载于:https://www.cnblogs.com/strengthen/p/10403265.html

[Swift]LeetCode528. 按权重随机选择 | Random Pick with Weight相关推荐

  1. Java实现 LeetCode 528 按权重随机选择(TreeMap)

    528. 按权重随机选择 给定一个正整数数组 w ,其中 w[i] 代表位置 i 的权重,请写一个函数 pickIndex ,它可以随机地获取位置 i,选取位置 i 的概率与 w[i] 成正比. 说明 ...

  2. 随机数生成生成器和力扣按权重随机选择 528

    随机数生成生成器和力扣按权重随机选择 528 在linux下内核有个专门内核模块进行生成随机数 /dev/random 不是很精准 /dev/urandom 更精准 原理 是内核的一个模块,专门产生的 ...

  3. 528. 按权重随机选择

    528. 按权重随机选择

  4. [528]. 按权重随机选择

    [528]. 按权重随机选择 题目 算法设计:加权随机取样 题目 传送门:528. 按权重随机选择 输入: ["Solution","pickIndex"] [ ...

  5. LeetCode 528. 按权重随机选择(前缀和+二分查找)

    文章目录 1. 题目 2. 解题 1. 题目 给定一个正整数数组 w ,其中 w[i] 代表下标 i 的权重(下标从 0 开始),请写一个函数 pickIndex ,它可以随机地获取下标 i,选取下标 ...

  6. 【LeetCode】528. Random Pick with Weight 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/random-pi ...

  7. leetcode 528. Random Pick with Weight

    给一个权重的vector,让你根据权重的概率返回值,返回的值是这些权重的索引. 比如给你一个[1,2]的权重矩阵,1/3的概率返回0,2/3的概率返回1. 等概率函数random只能等概率的一系列数, ...

  8. 根据权重做随机选择的算法

    1.随机选择算法. 要求是根据不同的权重值随机出现对应的气泡. 思路: 将所有的权重值相加,形成一个整体的区间[W1,W2],将每个权重都划分为小到子区间[w1,w2]. 每次做随机选择时,在整体的大 ...

  9. python random从集合中随机选择元素

    1.使用python random模块的choice方法随机选择某个元素 from random import choicefoo = ['a', 'b', 'c', 'd', 'e'] print ...

  10. python从数组中随机选择一些元素_numpy.random随机选择数组元素如何更高效

    最近在看代码库rlkit时,发现一句有意思的代码和注释(如下所示),大意是从列表中随机选择一个元素时使用np.random.randint比np.random.choice更加高效,相关的解释是np. ...

最新文章

  1. 2022-2028年中国海洋电力行业市场深度分析及发展策略分析报告
  2. exec的不同实现--鸠占鹊巢还是功成身退
  3. 部署Tomcat服务时,解决Cannot invoke Tomcat Manager 异常
  4. Linux之ping命令使用详解—网络故障定位(六)
  5. 工业用微型计算机(11)-指令系统(8)
  6. dojo——AMD(一、AMD中class使用)
  7. 面试遇Spark,别怂!
  8. SQL Server启动的几种方法
  9. 利用端口映射解决:拥有公网IP有限,内网需要访问因特网
  10. Git 本地分支关联远程分支
  11. paip.vs2010 或.net 4.0安装出错解决大法.
  12. 北大核心2020_“三个月不录用视为拒稿”,核心期刊投稿,编辑的这句话别有用意...
  13. 解决git报错:‘fatal: unable to access ‘https://XXX: Failed onnect to github. com port 443: Timed out
  14. EBS 12.1.3 应用打补丁操作及问题处理
  15. 风口下的追逐:AI正在驾驶、客服、教育领域疾驰
  16. 1148 数字字符出现频率
  17. 在excel/wps中如何实现批量翻译
  18. Android左右声道切换流程
  19. 大陆人怎么去香港银行开户?
  20. 删除设备和驱动器中的图标

热门文章

  1. 面试题之说几个Object类常用方法以及作用
  2. spring事务源码执行过程分析
  3. DockOne微信分享( 一零二):基于容器的日志管理实践
  4. WannaCry不相信眼泪 它需要你的安全防御与响应能力
  5. error CS1010 CS8025 CS1012 CS1525 常见文档错误解决
  6. HDFS中的NameNode和DataNode
  7. window.onerror=hide_error_message;
  8. ora-12514解决方法
  9. ubuntu如何修改terminal终端的主机名
  10. Pytorch:Tensor(张量)的使用