20170927_快排应用_数组中寻找第K小的数字
??????????????????????????????????????????????????????????????? ????????????????????????????????k???k??????????????????k????????????????????? ???????????????????????? ?Solution??????k??????? GetMinKthNumbers????????????????????? partition????????????????????? ???????????????????
发布日期:2021-04-30 21:12:29
浏览次数:114
分类:精选文章
本文共 1936 字,大约阅读时间需要 6 分钟。
???????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; }
??
??????????????????????????O(n log n)?????????k?????
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2026年06月01日 07时49分20秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
php中使用ajax进行前后端json数据交互
2023-02-28
Redis事务和锁操作
2023-02-28
PHP中如何得到数组的长度
2023-02-28
php中引入文件几种方式的区别
2023-02-28
PHP中把stdClass Object转array的几个方法
2023-02-28
PHP中替换换行符
2023-02-28
PHP中有关正则表达式的函数集锦
2023-02-28
Redis 集群搭建详细指南
2023-02-28
php中的cookie用法
2023-02-28
php中的session用法
2023-02-28
php中级联,php实现三级级联下拉框_PHP
2023-02-28
PHP中获取星期的几种方法
2023-02-28
Redis 限速器及问题
2023-03-01
php中高级基础知识点
2023-03-01
php中,如何将编译后的代码,反编译回去。
2023-03-01
php之aop实践
2023-03-01
PHP之APC缓存详细介绍(转)
2023-03-01
php之memcache,memcached
2023-03-01
php之引用
2023-03-01
PHP之数组和函数的基本教程
2023-03-01