Leetcode 215.数组中第k个最大元素 (每日一题 20210713)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 215.数组中第k个最大元素 (每日一题 20210713)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定整數(shù)數(shù)組 nums 和整數(shù) k,請返回?cái)?shù)組中第 k 個(gè)最大的元素。請注意,你需要找的是數(shù)組排序后的第 k 個(gè)最大的元素,而不是第 k 個(gè)不同的元素。示例 1:輸入: [3,2,1,5,6,4] 和 k = 2
輸出: 5
示例?2:輸入: [3,2,3,1,2,4,5,5,6] 和 k = 4
輸出: 4鏈接:https://leetcode-cn.com/problems/kth-largest-element-in-an-arrayclass Solution:def findKthLargest(self, nums: List[int], k: int) -> int:def findTopKth(low, high):privot = random.randint(low, high)nums[privot], nums[low] = nums[low], nums[privot]i, j = low, low + 1base = nums[low]while j <= high:if nums[j] > base:nums[i+1], nums[j] = nums[j],nums[i+1]i += 1j += 1nums[i], nums[low] = nums[low], nums[i]if i == k - 1:return nums[i]elif i > k - 1:return findTopKth(low, i-1)else:return findTopKth(i+1, high)return findTopKth(0, len(nums)-1)class Solution:def findKthLargest(self, nums: List[int], k: int) -> int:sort_num = sorted(nums)return sort_num[::-1][k-1]
總結(jié)
以上是生活随笔為你收集整理的Leetcode 215.数组中第k个最大元素 (每日一题 20210713)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 94.二叉树的中序遍历
- 下一篇: Leetcode 136.只出现一次的数