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 };
  • 相关阅读:
    【编程题目】左旋转字符串 ☆
    360測试开发笔试题(2016内推)
    start_kernel——boot_cpu_init及PER_CPU
    UVa 10673
    【面试】-Java基础知识
    Navgationcontroller 的pop
    别拿接口不当开发
    C++基础学习教程(三)
    安卓版微信自带浏览器和IE6浏览器ajax请求abort错误处理
    【动态树问题】LCT学习笔记
  • 原文地址:https://www.cnblogs.com/timesdaughter/p/5579565.html
Copyright © 2011-2022 走看看