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

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

    法一:

    1、先排序(O(n*logN))

    2、返回n-k个元素

    1  int findKthLargest(vector<int>& nums, int k) {
    2         //S1 sort函数 时间复杂度O(logN*N)
    3         int n = nums.size();
    4         std::sort(nums.begin(),nums.end());
    5         int result = nums[n-k];
    6         return result;
    7         }

    法二:快速选择(随机选择)

    1、同快排类似,但是每次划分只需要关注划分中的一段。

    2、最差时间复杂度O(n*n),但出现可能性很低。

        时间复杂度的期望为O(n)

     1 class Solution {
     2     
     3 public:
     4     int findKthLargest(vector<int>& nums, int k) {
     5       
     6         //S5 quickSelect
     7         return quickSelect(nums,0,nums.size()-1,k);
     8         
     9     }
    10      int quickSelect(vector<int>& nums,int start,int end,int k){
    11          if(start == end) return nums[start];
    12          int pivot;
    13          pivot = randPartition(nums,start,end);
    14          if(end-pivot+1 == k) {return nums[pivot];}
    15          if(end-pivot+1 > k){
    16             return quickSelect(nums,pivot+1,end,k);
    17          }
    18          if(end-pivot+1 < k){
    19             return quickSelect(nums,start,pivot-1,pivot+k-end-1);
    20          }
    21     
    22          return -1;
    23      }
    24      int randPartition(vector<int>& nums,int start ,int end){
    25          int randi = std::rand()%(end-start+1)+start;
    26          std::swap(nums[randi],nums[start]);
    27          int pivot = nums[start];
    28          int i = start;
    29          for(int j = start+1;j<=end;j++){
    30                 if(nums[j]<pivot){
    31                     i++;
    32                     swap(nums[i],nums[j]);
    33                 }
    34             }
    35             swap(nums[start],nums[i]);
    36         return i;
    37         }
    38        
    39 };
  • 相关阅读:
    商务通服务器版LR_Data目录下相关配置文件
    Python入门神图
    你不知道的JavaScript-2.词法作用域
    你不知道的JavaScript-1.作用域是什么
    linux服务器对外打包处理
    C# Form 关闭按钮灰化
    Spread常用属性
    Spread 常用属性
    C#打开关闭窗体事件顺序
    sqlserver如何使用日期计算
  • 原文地址:https://www.cnblogs.com/timesdaughter/p/5579565.html
Copyright © 2011-2022 走看看