博客
关于我
【ACWing】53. 最小的k个数
阅读量:241 次
发布时间:2019-02-28

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

要解决从n个整数中找出k个最小数的问题,可以使用Quick Select算法。该算法通过递归选择数组中的中间元素作为枢轴,将数组划分为左右两部分,然后确定目标元素所在的子数组继续查找。以下是详细的解决方法:

方法思路

  • 问题分析:我们需要从n个整数中找出k个最小的数,并按升序排列。常见的方法有Heap和Quick Select算法,这里选择Quick Select。
  • 算法选择:Quick Select算法类似于快速排序,通过选择中间元素作为枢轴,将数组分为左右两部分,递归处理子数组,直到找到目标位置。
  • 优化思路:选择中间元素作为枢轴,调整左右指针,交换元素位置,并根据枢轴位置决定递归方向。这种方法的时间复杂度为O(n + k log k),空间复杂度为O(log n)。
  • 解决代码

    #include 
    #include
    #include
    using namespace std;class Solution {public: void quick_select(vector
    &v, int l, int r, int idx) { if (l >= r) return; int mid = l + (r - l) / 2; int x = v[mid]; int i = l, j = r; while (i <= j) { while (v[i] < x) i++; while (v[j] > x) j--; if (i <= j) { swap(v[i], v[j]); i++; j--; } } if (idx <= j) { quick_select(v, l, j, idx); } else if (idx >= i) { quick_select(v, i, r, idx); } } vector
    getLeastNumbers_Solution(vector
    input, int k) { if (k == 0) return {}; if (k == input.size()) { sort(input.begin(), input.end()); return input; } quick_select(input, 0, input.size() - 1, k - 1); sort(input.begin(), input.begin() + k); vector
    res; for (int i = 0; i < k; ++i) { res.push_back(input[i]); } return res; }};int main() { vector
    input = {1, 2, 3, 4, 5}; int k = 3; Solution sol; vector
    result = sol.getLeastNumbers_Solution(input, k); for (int num : result) { cout << num << " "; } return 0;}

    代码解释

  • 类定义Solution类包含两个成员函数quick_selectgetLeastNumbers_Solution
  • 快速选择函数quick_select递归地选择中间元素作为枢轴,调整指针i和j,直到找到目标位置。
  • 获取最小数函数getLeastNumbers_Solution调用quick_select,然后对前k个元素排序并返回结果。
  • 主函数:读取输入数组,调用解决方案函数,并输出结果。
  • 通过这种方法,我们可以高效地从数组中找出k个最小的数,并按升序排列。

    转载地址:http://xqjs.baihongyu.com/

    你可能感兴趣的文章
    Python NLP完整项目实战教程(1)
    查看>>
    Python NLP自然语言处理详解
    查看>>
    python nltk nltk_data 离线安装,chatterbot
    查看>>
    Redis 限流的 3 种方式,还有谁不会?
    查看>>
    Python这么慢,为啥大公司还在用?
    查看>>
    python note 06 编码方式
    查看>>
    python numba 转灰度图_使用NumPy、Numba的简单使用(二)
    查看>>
    Python Numpy 关于 linspace()函数 使用详解(全)
    查看>>
    Python numpy插入、读取至postgreSQL数据库中bytea类型字段
    查看>>
    Python numpy数据的保存和读取
    查看>>
    python numpy矩阵索引_python – 在2D numpy ndarray或numpy矩阵中获取前N个值的索引
    查看>>
    Python OCR库:自动化测试验证码识别神器!
    查看>>
    python opencv - 斑点检测或圆形检测
    查看>>
    Python还可以做情感分析你不看看吗?
    查看>>
    Python OpenCV HoughLinesP 无法检测线
    查看>>
    Python OpenCV-使用透明度覆盖图像
    查看>>
    python Opencv图像基础操作
    查看>>
    Python OpenCV将图像转换为字节字符串?
    查看>>
    python OpenCV视频的读取及保存
    查看>>
    python open和file的区别
    查看>>