Kth Largest Element in an Array in Python


Suppose we have an unsorted array, we have to find the kth largest element from that array. So if the array is [3,2,1,5,6,4] and k = 2, then the result will be 5.

To solve this, we will follow these steps −

  • We will sort the element,

  • if the k is 1, then return last element, otherwise return array[n – k], where n is the size of the array.

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def findKthLargest(self, nums, k):
      """
      :type nums: List[int]
      :type k: int
      :rtype: int
      """
      nums.sort()
      print(nums)
      if k ==1:
         return nums[-1]
      temp = 1
      return nums[len(nums)-k]

Input

[56,14,7,98,32,12,11,50,45,78,7,5,69]
5

Output

50
raja
Published on 05-Feb-2020 10:03:29
Advertisements