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 };
  • 相关阅读:
    马哥博客作业第四周
    马哥博客作业第三周
    马哥博客作业第二周
    马哥博客作业第一周
    YUM常用命令
    RPM常用命令
    马哥博客作业第五周
    《现代操作系统》—— 第9章 文件系统(一)
    《现代操作系统》—— 第8章 存储模型(二) 虚拟存储技术
    《现代操作系统》—— 第7章 存储模型(一)
  • 原文地址:https://www.cnblogs.com/timesdaughter/p/5579565.html
Copyright © 2011-2022 走看看