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 };
  • 相关阅读:
    Android开发:关于WebView
    PHP+JQUEY+AJAX实现分页
    Bootstrap入门(二)栅格
    BootStrap入门教程 (一)
    mac 终端命令
    没有功能需求设计文档?对不起,拒绝开发!
    React 入门教程
    Webpack+React+ES6开发模式入门指南
    webpack2.0+ vue2.0
    一个小时学会jQuery
  • 原文地址:https://www.cnblogs.com/timesdaughter/p/5579565.html
Copyright © 2011-2022 走看看