1. 程式人生 > >Leetcode 215. 數組中的第K個最大元素 By Python

Leetcode 215. 數組中的第K個最大元素 By Python

class bject 不同 lee etc lar code 輸出 找到

在未排序的數組中找到第 k 個最大的元素。請註意,你需要找的是數組排序後的第 k 個最大的元素,而不是第 k 個不同的元素。

示例 1:

輸入: [3,2,1,5,6,4] 和 k = 2
輸出: 5

示例 2:

輸入: [3,2,3,1,2,4,5,5,6] 和 k = 4
輸出: 4

思路

一個sorted再直接返回第K個最大元素就好了

代碼

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        return sorted(nums)[-k]

Leetcode 215. 數組中的第K個最大元素 By Python