File tree Expand file tree Collapse file tree 2 files changed +71
-0
lines changed
lcof2/剑指 Offer II 071. 按权重生成随机数 Expand file tree Collapse file tree 2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change @@ -222,6 +222,44 @@ func (this *Solution) PickIndex() int {
222
222
*/
223
223
```
224
224
225
+ #### Swift
226
+
227
+ ``` swift
228
+ class Solution {
229
+ private var presum: [Int ]
230
+
231
+ init (_ w : [Int ]) {
232
+ let n = w.count
233
+ presum = [Int ](repeating : 0 , count : n + 1 )
234
+ for i in 0 ..< n {
235
+ presum[i + 1 ] = presum[i] + w[i]
236
+ }
237
+ }
238
+
239
+ func pickIndex () -> Int {
240
+ let n = presum.count
241
+ let x = Int .random (in : 1 ... presum [n - 1 ])
242
+ var left = 0
243
+ var right = n - 2
244
+ while left < right {
245
+ let mid = (left + right) >> 1
246
+ if presum[mid + 1 ] >= x {
247
+ right = mid
248
+ } else {
249
+ left = mid + 1
250
+ }
251
+ }
252
+ return left
253
+ }
254
+ }
255
+ /**
256
+ * Your Solution object will be instantiated and called as such:
257
+ * let w = [1]
258
+ * let solution = Solution(w)
259
+ * solution.pickIndex()
260
+ */
261
+ ```
262
+
225
263
<!-- tabs:end -->
226
264
227
265
<!-- solution:end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private var presum : [ Int ]
3
+
4
+ init ( _ w: [ Int ] ) {
5
+ let n = w. count
6
+ presum = [ Int] ( repeating: 0 , count: n + 1 )
7
+ for i in 0 ..< n {
8
+ presum [ i + 1 ] = presum [ i] + w[ i]
9
+ }
10
+ }
11
+
12
+ func pickIndex( ) -> Int {
13
+ let n = presum. count
14
+ let x = Int . random ( in: 1 ... presum [ n - 1 ] )
15
+ var left = 0
16
+ var right = n - 2
17
+ while left < right {
18
+ let mid = ( left + right) >> 1
19
+ if presum [ mid + 1 ] >= x {
20
+ right = mid
21
+ } else {
22
+ left = mid + 1
23
+ }
24
+ }
25
+ return left
26
+ }
27
+ }
28
+ /**
29
+ * Your Solution object will be instantiated and called as such:
30
+ * let w = [1]
31
+ * let solution = Solution(w)
32
+ * solution.pickIndex()
33
+ */
You can’t perform that action at this time.
0 commit comments