Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2 Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
My Tests
import pytest from .Day16_KthLargestElementInAnArray import Solution s = Solution() @pytest.mark.parametrize( "nums,k,expected", [ ([3,2,1,5,6,4], 2, 5), ([3,2,3,1,2,4,5,5,6], 4, 4), ], ) def test_get_maximum_generated(nums, k, expected): assert s.findKthLargest(nums, k) == expected
My Solution
from typing import List class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: return sorted(nums)[len(nums) - k]
Analysis
My Commentary
Sorting the array and finding the kth from the end is clearly not the best solution but it's the simplest and it's Saturday.
Top comments (0)