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 };
  • 相关阅读:
    iOS开发---业务逻辑
    iOS 蓝牙功能 bluetooth
    iOS 企业版 安装失败 原因
    iOS 生命周期 -init、viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear、viewDidDisappear 区别和用途
    iOS 7 修改默认布局从status bar 底部开始
    企业打包时不能安装原因
    UISegmentedControl 功能简单 分析
    ios 推送 证书配置
    ios 获取手机设备信息
    创建quickstart报错
  • 原文地址:https://www.cnblogs.com/timesdaughter/p/5579565.html
Copyright © 2011-2022 走看看