zoukankan      html  css  js  c++  java
  • 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.

    求第K大的数

    C++:快排思想

     1 class Solution {
     2 public:
     3     int findKthLargest(vector<int>& nums, int k) {
     4         k = nums.size() - k ;
     5         int left = 0 ;
     6         int right = nums.size() - 1 ;
     7         while(left < right){
     8             int index = partation(nums,left,right) ;
     9             if (index == k){
    10                 break ;
    11             }else if(index < k){
    12                 left = index + 1 ;
    13             }else{
    14                 right = index - 1 ;
    15             }
    16         }
    17         return nums[k] ;
    18     }
    19     
    20     int partation(vector<int>& nums, int left , int right) {
    21         int k = left ;
    22         for(int i = left ; i < right ; i++){
    23             if (nums[i] < nums[right]){
    24                 swap(nums[k++] , nums[i]) ;
    25             }
    26         }
    27         swap(nums[k] , nums[right]) ;
    28         return k ;
    29     }
    30 };

    java: 最大堆  求第2大的数可以转化为求第5小的数

     1 class Solution {
     2     public int findKthLargest(int[] nums, int k) {
     3         PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>((o1,o2) -> o2-o1) ;
     4         k = nums.length-k+1 ;
     5         for(int num : nums){
     6             if (minHeap.size() < k){
     7                 minHeap.add(num) ;
     8             }else if(minHeap.peek() > num){
     9                 minHeap.poll() ;
    10                 minHeap.add(num) ;
    11             }
    12         }
    13         return minHeap.peek() ;
    14     }
    15 }
  • 相关阅读:
    DRF的Filter:字段过滤,查找,排序
    DRF的ViewSet和Router
    DRF的APIView和mixins+GenericAPIView和ListAPIView
    DRF的Serializer和ModelSerializer
    html5中的drag
    excel与json转换
    call和bind的原生实现
    将字符串转化为条形码,在将canvas转化为图片
    JSON与excel之间的相互转化(Vue)
    js实现点击复制,将内容复制至剪贴板
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/10267237.html
Copyright © 2011-2022 走看看