博客
关于我
【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/

    你可能感兴趣的文章
    none 和 host 网络的适用场景 - 每天5分钟玩转 Docker 容器技术(31)
    查看>>
    None还可以是函数定义可选参数的一个默认值,设置成默认值时实参在调用该函数时可以不输入与None绑定的元素...
    查看>>
    NoNodeAvailableException None of the configured nodes are available异常
    查看>>
    Vue.js 学习总结(16)—— 为什么 :deep、/deep/、>>> 样式能穿透到子组件
    查看>>
    nopcommerce商城系统--文档整理
    查看>>
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NoSQL介绍
    查看>>
    NoSQL数据库概述
    查看>>
    Notadd —— 基于 nest.js 的微服务开发框架
    查看>>
    NOTE:rfc5766-turn-server
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>