File tree 2 files changed +57
-0
lines changed
2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -150,6 +150,37 @@ func beautifulBouquet(flowers []int, cnt int) (ans int) {
150
150
}
151
151
```
152
152
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
+
153
184
<!-- tabs: end -->
154
185
155
186
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments