zoukankan      html  css  js  c++  java
  • 第k小的元素

    利用快排思想,如果标志位大于k,则第k小的数字在左边,否则在右边。(程序是第k大的元素)

    #include <iostream>
    #include <vector>
    using namespace std;
    
    //求向量中第k大的数字,从大到小进行排列
    
    int q_sort(vector<int> &v, int low, int high)
    {
        int tmp = v[low];
        
        while (low < high)
        {
            while (low<high && v[high] <= tmp)
                --high;
            v[low] = v[high];
    
            while (low<high && v[low] >= tmp)
                ++low;
            v[high] = v[low];    
        }
        v[low] = tmp;
        cout << low << endl;
        for (auto &i : v)
            cout << i << " ";
        cout << endl;
        return low;
    }
    int k_max(vector<int> &v, int low, int high,int k)
    {
        if (low >= high)
            return v[low];
        else 
        {
            int mid = q_sort(v, low, high);
            if (mid>k)
                k_max(v, low, mid - 1,k);
            else if (mid < k)
                k_max(v, mid + 1, high,k);
            else
                return v[mid];
        }
    
    }
    
    int main()
    {
        vector<int> v = { 78, 23, 64, 1, 35, 98, 45, 61, 32, 845, 223 };
        int len = v.size();
        int k_num=k_max(v, 0, len - 1, 3-1);    //此处为k-1,从大到小的排列,下标为k-1的数。
        cout << k_num << endl;
        return 0;
    }
  • 相关阅读:
    【KVM系列 virt-v2v】virt-v2v过程中的报错
    大机与超级计算机的区别
    多路径 on linux
    ansible 管控 windows
    Linux启动盘
    RHCA 环境命令
    Xshell 4 连接 Ubuntu/Kali 报错 "找不到匹配的key exchange算法"
    security group & ACL
    windows powercfg
    OKD
  • 原文地址:https://www.cnblogs.com/wang-130213/p/9199314.html
Copyright © 2011-2022 走看看