zoukankan      html  css  js  c++  java
  • 查找第K大的数

    类快排 第一种方法 o(n)

    2019.06.08更正错误

    #include <bits/stdc++.h>
    using namespace std;
    
    const int N = 1000;
    
    int s[N];
    
    int partion(int l,int r) {
        int tmp = s[l];
        int i = l, j = r;
        while(i < j) {
            while(i < j && s[j] >= tmp) j--;
            while(i < j && s[i] <= tmp) i++;
            if(i < j) {
                swap(s[i], s[j]);
            }
        }
        // now i == j
        swap(s[i], s[l]);
        return i;
    }
    
    
    void selectKth(int l,int r,int k) {
        if(l > r)
            return ;
        int c = partion(l,r);
        if(c == k)
            return ;
        else if(c < k)
            selectKth(c+1,r,k);
        else
            selectKth(l,c,k);
    }
    
    int main()
    {
        srand(time(NULL));
        int n = 10;
        int m = 10;
    
        for(int i=1; i<=n; i++)
            s[i] = rand() % 15;
        int k = 5;
        selectKth(1,n,k);
        printf("%d
    ", s[k]);
        sort(s+1,s+11);
        printf("%d
    ", s[k]);
    
        return 0;
    }
    

    第二种方法 用到堆了

    大根堆 是arr[i] <= arr[2i+1] && arr[i] <= arr[2i], 因此大根堆的堆顶是最小值,所以排序的话呢,就是从小到大排的...

    priority_queue<int> que;
    int k = 5;
    for(int i=1; i<=n; i++) {
        que.push(s[i]);
        if(que.size() > k) {
            que.pop();
        }
    }
    cout<<que.top()<<endl;   
    
  • 相关阅读:
    初识 vue
    Spring boot 整合 Swagger
    Swagger 注解
    初识 Swagger
    初识 mycat
    SpringBoot中的国际化
    为什么博客园用户体验这么差?
    Numpy常用方法及应用总汇
    嵌入式开发10种常见数字滤波算法
    .gitignore使用
  • 原文地址:https://www.cnblogs.com/Draymonder/p/10562257.html
Copyright © 2011-2022 走看看