Find the Kth Largest Integer in the Array
Table of Contents
Find the Kth Largest Integer in the Array
Problem Statement
You are given an array of strings nums
and an integer k
. Each string in nums
represents an integer without leading zeros.
Return the string that represents the kth
largest integer in nums
.
Note: Duplicate numbers should be counted distinctly. For example, if nums
is ["1","2","2"]
, "2"
is the first largest integer, "2"
is the second-largest integer, and "1"
is the third-largest integer.
Example 1:
Input: nums = ["3","6","7","10"], k = 4 Output: "3" Explanation: The numbers in nums sorted in non-decreasing order are ["3","6","7","10"]. The 4th largest integer in nums is "3".
Example 2:
Input: nums = ["2","21","12","1"], k = 3 Output: "2" Explanation: The numbers in nums sorted in non-decreasing order are ["1","2","12","21"]. The 3rd largest integer in nums is "2".
Example 3:
Input: nums = ["0","0"], k = 2 Output: "0" Explanation: The numbers in nums sorted in non-decreasing order are ["0","0"]. The 2nd largest integer in nums is "0".
Constraints:
1 <= k <= nums.length <= 104
1 <= nums[i].length <= 100
nums[i]
consists of only digits.nums[i]
will not have any leading zeros.
Golang solution
type Minheap []string
func (h Minheap) Len() int {
return len(h)
}
func (h Minheap) Less(i, j int) bool {
// check if lengths are same
if len(h[i]) == len(h[j]) {
return h[i] < h[j]
}
// return based on lexographical order
return len(h[i]) < len(h[j])
}
func (h Minheap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h *Minheap) Push(item interface{}) {
*h = append(*h, item.(string))
}
func (h *Minheap) Pop() interface{} {
length := len(*h)
item := (*h)[length-1]
(*h) = (*h)[0 : length-1]
return item
}
func kthLargestNumber(nums []string, k int) string {
h := &Minheap{}
heap.Init(h)
for _, val := range nums {
// v, _ := strconv.ParseUint(val, 10, 64)
// heap.Push(h, v)
heap.Push(h, val)
// keep total items in heap at most k
if h.Len() > k {
heap.Pop(h)
}
}
// result := []string{}
// for h.Len() > 0 {
// item := heap.Pop(h)
// result = append(result, item.(string))
// }
ans := heap.Pop(h).(string)
return ans
}
Output
Input
nums = ["3","6","7","10"]
k = 4
Output
"3"
Please visit https: https://codeandalgo.com for more such contents