find the kth largest element in an array in go

One way to find the kth largest element in an array is to sort the array in descending order and return the kth element. Here's an example implementation in Go:

main.go
func findKthLargest(nums []int, k int) int {
    sort.Sort(sort.Reverse(sort.IntSlice(nums)))
    return nums[k-1]
}
117 chars
5 lines

The sort.Sort function is used to sort the array in descending order, and sort.Reverse is used to reverse the order of the sort.IntSlice type (which implements the sort.Interface interface required by the sort.Sort function).

Then, we simply return the element at index k-1 (assuming indexing starts at 0).

Note that this solution has a time complexity of O(n log n), where n is the length of the input array, due to the use of the sorting algorithm. There are other algorithms such as QuickSelect that can solve this problem in O(n) time complexity.

related categories

gistlibby LogSnag