Skip to content

feat: add swift implementation to lcof2 problem: No.071 #3223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,44 @@ func (this *Solution) PickIndex() int {
*/
```

#### Swift

```swift
class Solution {
private var presum: [Int]

init(_ w: [Int]) {
let n = w.count
presum = [Int](repeating: 0, count: n + 1)
for i in 0..<n {
presum[i + 1] = presum[i] + w[i]
}
}

func pickIndex() -> Int {
let n = presum.count
let x = Int.random(in: 1...presum[n - 1])
var left = 0
var right = n - 2
while left < right {
let mid = (left + right) >> 1
if presum[mid + 1] >= x {
right = mid
} else {
left = mid + 1
}
}
return left
}
}
/**
* Your Solution object will be instantiated and called as such:
* let w = [1]
* let solution = Solution(w)
* solution.pickIndex()
*/
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
private var presum: [Int]

init(_ w: [Int]) {
let n = w.count
presum = [Int](repeating: 0, count: n + 1)
for i in 0..<n {
presum[i + 1] = presum[i] + w[i]
}
}

func pickIndex() -> Int {
let n = presum.count
let x = Int.random(in: 1...presum[n - 1])
var left = 0
var right = n - 2
while left < right {
let mid = (left + right) >> 1
if presum[mid + 1] >= x {
right = mid
} else {
left = mid + 1
}
}
return left
}
}
/**
* Your Solution object will be instantiated and called as such:
* let w = [1]
* let solution = Solution(w)
* solution.pickIndex()
*/
Loading