0
点赞
收藏
分享

微信扫一扫

【算法导论】数组中的第K个最大元素-countingsort 计数排序

善解人意的娇娇 2022-04-26 阅读 58
c++

 代码如下:①

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
  int len=nums.size();
     if(len == 0)
         return 0;
        vector<int>tempArr(nums.begin(),nums.end());//原始数组的拷贝
        // search for the minist,maxist
        int min = tempArr[0];
        int max = min;
        for(int i=1 ; i<len ; i++)
        {
            if(min> tempArr[i])
                min = tempArr[i];
            if(max < tempArr[i])
                max = tempArr[i];
        }
        
        // deal with count[key]
        const int key = max - min +1;
        int count[key] ;
        for(int i=0;i<key;i++)
        {
            count[i]=0;
        }
        for(int i=0;i<len;i++)
        {
            ++count[tempArr[i] - min];
            // subtract min, array count start from 0
        }
        for(int i=1;i<key;i++)
        {
            count[i] += count[i-1];
            // add up
        }
        
        for(int i=len-1;i>=0;i--)
            nums[--count[tempArr[i] - min ]] = tempArr[i];
        
        return nums[len-k];
    }
};

(代码①未通过oj)

代码②:通过oj

分治思想

#include<iostream>

using namespace std;
int partition(int a[], int left, int right){
 int i = left;  
 int j = right;  
 int mid = a[left]; 
 while (i < j){
  while (i < j && a[j] >= mid){
   j--;
  }
  if (i < j){
   a[i++] = a[j];   
  }
  while (i < j && a[i] < mid){
   i++;
  }
  if (i < j)  {
   a[j--] = a[i];   
  }
 }
 a[i] = mid;
 return i;  
}
void quicksort(int a[], int left, int right){
 if (left < right){
  int m = partition(a, left, right); 
  quicksort(a, left, m - 1);   
  quicksort(a, m + 1, right);   
 }
}

int main(){
int a[100];
 int x;
 int i = 0;
 while (cin >> x) {
  a[i++] = x;
  if (cin.get() == '\n') break;
 }
 int n;
 cin >> n;
 quicksort(a, 0, i - 1); 
 cout << a[n - 1];

 return 0;
}
举报

相关推荐

0 条评论