-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1985-find-the-kth-largest-integer-in-the-array.kt
61 lines (53 loc) · 1.4 KB
/
1985-find-the-kth-largest-integer-in-the-array.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* Using a minHeap (And BigInteger, alternativly you can compare strings too)
*/
class Solution {
fun kthLargestNumber(nums: Array<String>, k: Int): String {
val minHeap = PriorityQueue<BigInteger>{ a, b ->
if(a < b)
1
else
-1
}
nums.forEach {
minHeap.add(it.toBigInteger())
}
var kth = k
while(kth > 1) {
minHeap.poll()
kth--
}
return minHeap.poll().toString()
}
}
/*
* Using a maxHeap (And comparing strings, alternativly you can use BigInteger too)
*/
class Solution {
fun kthLargestNumber(nums: Array<String>, k: Int): String {
val minHeap = PriorityQueue<String>{ a, b ->
if(a.length > b.length)
1
else if(a.length < b.length)
-1
else {
var toReturn = 0
for(i in 0 until a.length) {
if(a[i] > b[i]) {
toReturn = 1
break
} else if(a[i] < b[i]){
toReturn = -1
break
}
}
toReturn
}
}
nums.forEach {
minHeap.add(it)
if(minHeap.size > k) minHeap.poll()
}
return minHeap.peek()
}
}