Skip to content
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

feat: add swift implementation to lcp problem: No.18 #3754

Merged
merged 3 commits into from
Nov 12, 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
31 changes: 31 additions & 0 deletions lcp/LCP 18. 早餐组合/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,37 @@ func breakfastNumber(staple []int, drinks []int, x int) int {
}
```

#### Swift

```swift
class Solution {
func breakfastNumber(_ staple: [Int], _ drinks: [Int], _ x: Int) -> Int {
let mod = 1000000007
var result = 0
let sortedDrinks = drinks.sorted()

for s in staple {
let remaining = x - s
if remaining >= sortedDrinks.first ?? 0 {
var left = 0
var right = sortedDrinks.count - 1

while left < right {
let mid = (left + right + 1) / 2
if sortedDrinks[mid] <= remaining {
left = mid
} else {
right = mid - 1
}
}
result = (result + left + 1) % mod
}
}
return result
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
26 changes: 26 additions & 0 deletions lcp/LCP 18. 早餐组合/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution {
func breakfastNumber(_ staple: [Int], _ drinks: [Int], _ x: Int) -> Int {
let mod = 1000000007
var result = 0
let sortedDrinks = drinks.sorted()

for s in staple {
let remaining = x - s
if remaining >= sortedDrinks.first ?? 0 {
var left = 0
var right = sortedDrinks.count - 1

while left < right {
let mid = (left + right + 1) / 2
if sortedDrinks[mid] <= remaining {
left = mid
} else {
right = mid - 1
}
}
result = (result + left + 1) % mod
}
}
return result
}
}