Skip to content

Commit e293766

Browse files
klever34yanglbme
andauthored
feat: add swift implementation to lcof2 problem: No.059 (doocs#3102)
* feat: add swift implementation to lcof2 problem: No.059 * style: format code and docs with prettier --------- Co-authored-by: Libin YANG <[email protected]>
1 parent a4c6ecc commit e293766

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

lcof2/剑指 Offer II 059. 数据流的第 K 大数值/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,39 @@ func (h *IntHeap) Top() int {
225225
*/
226226
```
227227

228+
#### Swift
229+
230+
```swift
231+
import Collections
232+
233+
class KthLargest {
234+
private var h: Heap<Int>
235+
private var size: Int
236+
237+
init(_ k: Int, _ nums: [Int]) {
238+
h = Heap()
239+
size = k
240+
for x in nums {
241+
add(x)
242+
}
243+
}
244+
245+
func add(_ val: Int) -> Int {
246+
h.insert(val)
247+
if h.count > size {
248+
h.removeMin()
249+
}
250+
return h.min!
251+
}
252+
}
253+
254+
/**
255+
* Your KthLargest object will be instantiated and called as such:
256+
* let obj = KthLargest(k, nums)
257+
* let ret_1: Int = obj.add(val)
258+
*/
259+
```
260+
228261
<!-- tabs:end -->
229262

230263
<!-- solution:end -->
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import Collections
2+
3+
class KthLargest {
4+
private var h: Heap<Int>
5+
private var size: Int
6+
7+
init(_ k: Int, _ nums: [Int]) {
8+
h = Heap()
9+
size = k
10+
for x in nums {
11+
add(x)
12+
}
13+
}
14+
15+
func add(_ val: Int) -> Int {
16+
h.insert(val)
17+
if h.count > size {
18+
h.removeMin()
19+
}
20+
return h.min!
21+
}
22+
}
23+
24+
/**
25+
* Your KthLargest object will be instantiated and called as such:
26+
* let obj = KthLargest(k, nums)
27+
* let ret_1: Int = obj.add(val)
28+
*/

0 commit comments

Comments
 (0)