日16 -配列のKth最大要素


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.


例1 :
Input: [3,2,1,5,6,4] and k = 2
Output: 5
例2 :
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
注意:
あなたはkが常に有効であると仮定するかもしれません、1≤ ケイ≤ 配列の長さ.

マイテスト


Link to code
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

マイソリューション


Link to code
from typing import List


class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        return sorted(nums)[len(nums) - k]

分析




私の解説


配列をソートして、最後からkthを見つけることは明らかに最高の解決ではありませんが、それは最も簡単です、そして、それは土曜日です.