Skip to content

Commit 6b77fc8

Browse files
authored
feat: add swift implementation to lcp problem: No.68 (#4117)
1 parent 4a511eb commit 6b77fc8

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

lcp/LCP 68. 美观的花束/README.md

+31
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,37 @@ func beautifulBouquet(flowers []int, cnt int) (ans int) {
150150
}
151151
```
152152

153+
#### Swift
154+
155+
```swift
156+
class Solution {
157+
func beautifulBouquet(_ flowers: [Int], _ cnt: Int) -> Int {
158+
let mod = Int(1e9 + 7)
159+
var maxFlower = 0
160+
for flower in flowers {
161+
maxFlower = max(maxFlower, flower)
162+
}
163+
164+
var flowerCount = [Int](repeating: 0, count: maxFlower + 1)
165+
var ans = 0
166+
var j = 0
167+
168+
for i in 0..<flowers.count {
169+
flowerCount[flowers[i]] += 1
170+
171+
while flowerCount[flowers[i]] > cnt {
172+
flowerCount[flowers[j]] -= 1
173+
j += 1
174+
}
175+
176+
ans = (ans + (i - j + 1)) % mod
177+
}
178+
179+
return ans
180+
}
181+
}
182+
```
183+
153184
<!-- tabs:end -->
154185

155186
<!-- solution:end -->
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
func beautifulBouquet(_ flowers: [Int], _ cnt: Int) -> Int {
3+
let mod = Int(1e9 + 7)
4+
var maxFlower = 0
5+
for flower in flowers {
6+
maxFlower = max(maxFlower, flower)
7+
}
8+
9+
var flowerCount = [Int](repeating: 0, count: maxFlower + 1)
10+
var ans = 0
11+
var j = 0
12+
13+
for i in 0..<flowers.count {
14+
flowerCount[flowers[i]] += 1
15+
16+
while flowerCount[flowers[i]] > cnt {
17+
flowerCount[flowers[j]] -= 1
18+
j += 1
19+
}
20+
21+
ans = (ans + (i - j + 1)) % mod
22+
}
23+
24+
return ans
25+
}
26+
}

0 commit comments

Comments
 (0)