zoukankan      html  css  js  c++  java
  • LeetCode 数组中的第K个最大元素

    LeetCode   数组中的第K个最大元素

    在未排序的数组中找到第 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

    说明:

    你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。

    使用分治的思想,二分搜索

     1 class Solution:
     2     def _findKthLargest(self, nums, l, r, k):
     3         #注意需要进行降序排列
     4         if l >= r:
     5             return nums[k-1]
     6         #Partition
     7         pixvot = nums[l]
     8         i = l+1
     9         lt = l+1
    10         while i <= r:
    11             if nums[i] > pixvot:
    12                 nums[i], nums[lt] = nums[lt], nums[i]
    13                 i += 1
    14                 lt += 1
    15             else:
    16                 i += 1
    17         lt -= 1
    18         nums[l], nums[lt] = nums[lt], nums[l]
    19 
    20         if k-1 == lt:
    21             return nums[lt]
    22         elif k-1 > lt:
    23             #去右边找
    24             return self._findKthLargest(nums, lt+1, r, k)
    25         else:
    26             #去左边找
    27             return self._findKthLargest(nums, l, lt-1, k)
    28 
    29     def findKthLargest(self, nums, k):
    30         """
    31         :type nums: List[int]
    32         :type k: int
    33         :rtype: int
    34         """
    35         return self._findKthLargest(nums, 0, len(nums)-1, k)
  • 相关阅读:
    HDU 4608 I-number
    hdu 4607 ( Park Visit )
    ZROI十一集训Day2
    CodeForces1230
    模拟退火
    ZROI#1007
    ZROI#1006
    ZROI#1005
    ZROI#1004
    ZROI#962
  • 原文地址:https://www.cnblogs.com/yxh-amysear/p/9294380.html
Copyright © 2011-2022 走看看