Skip to content

Commit 8932678

Browse files
authored
feat: add swift implementation to lcof2 problem: No.071 (#3223)
1 parent 41d1468 commit 8932678

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

lcof2/剑指 Offer II 071. 按权重生成随机数/README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,44 @@ func (this *Solution) PickIndex() int {
222222
*/
223223
```
224224

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+
225263
<!-- tabs:end -->
226264

227265
<!-- solution:end -->
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
*/

0 commit comments

Comments
 (0)