20170927_快排应用_数组中寻找第K小的数字
发布日期:2021-04-30 21:12:29 浏览次数:114 分类:精选文章

本文共 1936 字,大约阅读时间需要 6 分钟。

???????k???????????????????????????????????????????

????

??????????????????????k????????????

  • ???????????????????????????????????????????????????????????????
  • ????????????????????????????????k???k??????????????????k?????????????????????
  • ????????????????????????
  • ???????????O(n log n)????????

    ????

    #include 
    #include
    #include
    using namespace std;
    class Solution {
    public:
    void GetMinKthNumbers(vector
    & input, int k) {
    int n = input.size();
    if (k > n || n <= 0 || k <= 0) {
    cout << -1 << endl;
    return;
    }
    int start = 0;
    int end = n - 1;
    int index = partition(input, start, end);
    while (index != k - 1) {
    if (index > k - 1) {
    end = index - 1;
    index = partition(input, start, end);
    } else {
    start = index + 1;
    index = partition(input, start, end);
    }
    }
    cout << input[index] << endl;
    }
    public:
    int partition(vector
    & input, int start, int end) {
    int n = input.size();
    if (n <= 1) return start;
    int i = start;
    int j = end;
    while (i < j) {
    while (i < j && input[i] <= input[j]) {
    ++i;
    }
    if (i < j) {
    swap(input[i], input[j]);
    ++i;
    }
    --j;
    }
    return i;
    }
    };
    int main() {
    vector
    input; string s = "{4,5,1,6,2,7,3,8}"; for (char ch : s) { if (ch == ',') continue; input.push_back(ch - '0'); } int k = 0; cin >> k; Solution solution; solution.GetMinKthNumbers(input, k); system("pause"); return 0; }

    ??

  • ?Solution??????k???????
  • GetMinKthNumbers?????????????????????
  • partition?????????????????????
  • ???????????????????
  • ??????????????????????????O(n log n)?????????k?????

    上一篇:Java基础知识之数据类型和运算符详解
    下一篇:内存泄漏与内存溢出的区别

    发表评论

    最新留言

    第一次来,支持一个
    [***.219.124.196]2026年06月01日 07时49分20秒