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

    For example,
    Given [3,2,1,5,6,4] and k = 2, return 5.

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

    思路:方法一:排序,然后输出第k个数。O(nlogn)。

    方法二:进行k次冒泡排序,然后输出倒数第k个数。O(nk)。

    方法三:构建一个大小为n的大顶堆,然后从中抽取k-1次最大值,之后堆顶的值就是第k大的数。复杂度为O(n + klogn)。

    下面附上方法三的代码。

     1 class Solution {
     2 public:
     3     int heap_size;
     4     void Max_Heapify(vector<int>& nums, int i)
     5     {
     6         int l = i * 2 + 1;
     7         int r = i * 2 + 2;
     8         int largest = i;
     9         if (l < heap_size && nums[l] > nums[i])
    10             largest = l;
    11         if (r < heap_size && nums[r] > nums[largest])
    12             largest = r;
    13         if (largest != i)
    14         {
    15             swap(nums[i], nums[largest]);
    16             Max_Heapify(nums, largest);
    17         }
    18     }
    19     void Build_MaxHeap(vector<int>& nums, int length)
    20     {
    21         heap_size = length;
    22         for (int i = heap_size / 2 - 1; i >= 0; i--)
    23             Max_Heapify(nums, i);
    24     }
    25     void Extract(vector<int>& nums)
    26     {
    27         if (heap_size == 0) return;
    28         swap(nums[0], nums[heap_size - 1]);
    29         heap_size--;
    30         Max_Heapify(nums, 0);
    31     }
    32     int findKthLargest(vector<int>& nums, int k) {
    33         Build_MaxHeap(nums, nums.size());
    34         for (int i = 1; i < k; i++)
    35             Extract(nums);
    36         return nums[0];
    37     }
    38 };
  • 相关阅读:
    杭电OJ-1031_Design T-Shirt
    杭电OJ-1036_Average is not Fast Enough!
    2019杭电多校一 L. Sequence (NTT)
    Binary Table CodeForces
    2019牛客多校一 H. XOR (线性基)
    Jzzhu and Numbers CodeForces
    Geometers Anonymous Club CodeForces
    [笔记] 扩展卢卡斯
    Luogu P2183 [国家集训队]礼物 扩展卢卡斯+组合数
    Luogu P4901 排队 fib数列+树状数组+倍增
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4949281.html
Copyright © 2011-2022 走看看