zoukankan      html  css  js  c++  java
  • 11-215. Kth Largest Element in an Array

    题目描述:

    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.

    Example 1:

    Input: [3,2,1,5,6,4] and k = 2
    Output: 5
    

    Example 2:

    Input: [3,2,3,1,2,4,5,5,6] and k = 4
    Output: 4

    Note: 
    You may assume k is always valid, 1 ≤ k ≤ array's length.

    代码:

     1 class Solution:
     2     def findKthLargest(self, nums, k) -> int:
     3         # shuffle nums to avoid n*n
     4         random.shuffle(nums)
     5         return self.quickSelection(nums, 0, len(nums) - 1, len(nums) - k)
     6 
     7     def quickSelection(self, nums, start, end, k):
     8         if start > end:
     9             return float('inf')
    10         pivot = nums[end]
    11         left = start
    12         for i in range(start, end):
    13             if nums[i] <= pivot:
    14                 # swip left and i
    15                 nums[left], nums[i] = nums[i], nums[left]
    16                 left += 1
    17         nums[left], nums[end] = nums[end], nums[left]
    18         if left == k:
    19             return nums[left]
    20         elif left < k:
    21             return self.quickSelection(nums, left + 1, end, k)
    22         else:
    23             return self.quickSelection(nums, start, left - 1, k)

    一个基于python的很好的分析:https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/301338/Python-or-tm-215

  • 相关阅读:
    python 模块包裹
    函数指针
    python界面
    python FileError
    python pickle
    python file
    python set
    python 字典的函数
    字典问题
    java学习笔记4
  • 原文地址:https://www.cnblogs.com/tbgatgb/p/10952819.html
Copyright © 2011-2022 走看看