本文主要是介绍leintcode Kth Largest Element python,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Description
Find K-th largest element in an array.
参考快速排序的思想
class Solution:"""@param n: An integer@param nums: An array@return: the Kth largest element"""def sort_info(self,begin,end,nums):if len(nums)==1:return 0,numstemp = nums[begin]less_index = beginmore_index = endflag = beginwhile(less_index< more_index):while(less_index< more_index and temp>=nums[more_index] and flag!= more_index):more_index -= 1while(less_index <= more_index and temp < nums[less_index] and flag != less_index):less_index += 1flag = more_index if flag==less_index else less_indexnums[less_index],nums[more_index] = nums[more_index],nums[less_index]return flag,numsdef kthLargestElement(self, n, nums):# write your code hereflag,nums = self.sort_info(0,len(nums)-1,nums)while(1) :if flag == n-1:return nums[n-1]elif flag > n-1:nums = nums[:flag]flag,nums = self.sort_info(0,len(nums)-1,nums)else:nums = nums[flag+1:]n = n - flag-1flag,nums = self.sort_info(0,len(nums)-1,nums)
这篇关于leintcode Kth Largest Element python的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!