题目

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

思考

  • 方法0: 直接排序然后返回前k个,最好的时间复杂度为 O(nlog(n))
  • 方法1: 快排的变种,时间复杂度 O(n),缺点:原址,需要把所有数都 load 到内存中
  • 方法2: 利用最大堆作为辅助,时间复杂度 O(n*lg(k)),适用于处理数据量很大的情况。

code


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution{
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k){
        vector<int> ans;
        if(k > input.size()){
            return ans;
        }

        // GetLeastNumbersPartition(input, 0, input.size()-1, k);
        // for(int i=0; i<k; i++)
        //  ans.push_back(input[i]);

        // return ans;

        return GetLeastNumbersHeap(input, k);
    }

    // parition, average time complexity - O(n)
    // note: k should less than then size of input
    void GetLeastNumbersPartition(vector<int> &input, int left, int right, int k){
        int pos = partition(input, left, right);
        if(pos == k-1){
            return;
        }else if (pos < k-1){
            GetLeastNumbersPartition(input, pos+1, right, k);
        }else{
            GetLeastNumbersPartition(input, left, pos-1, k);
        }
    }

    int partition(vector<int> &input, int left, int right){
        if(left > right)
            return -1;
        int pos = left-1;
        for(int i=left; i<right; i++){
            if(input[i] <= input[right]){
                swap(input[i], input[++pos]);
            }
        }

        swap(input[right], input[++pos]);
        // input[left, pos] <= input[pos]
        // input[pos+1, right] > input[pos]
        return pos;
    }

    // heap sort, time complexity - O(nlog(k))
    vector<int> GetLeastNumbersHeap(vector<int> &input, int k){

        if(k > input.size() || input.empty())
            return vector<int>();

        vector<int> ans(input.begin(), input.begin()+k); // max heap
        make_heap(ans.begin(), ans.end(), comp);

        for(int i=k; i<input.size(); i++){
            if(input[i] < ans.front()){ // the current value less than the maximun of heap
                pop_heap(ans.begin(), ans.end(), comp);
                ans.pop_back();

                ans.push_back(input[i]);
                push_heap(ans.begin(), ans.end(), comp);
            }
        }

        sort(ans.begin(), ans.end());

        return ans;
    }

    static bool comp(int a, int b){
        return a<b;
    }

};

int main()
{
    freopen("in.txt", "r", stdin);
    int k;

    cin >> k;

    vector<int> input;
    int cur;
    while(cin >> cur){
        input.push_back(cur);
    }

    vector<int> ans = Solution().GetLeastNumbers_Solution(input, k);

    for(int n : ans)
        cout << n << " ";
    cout << endl;

    fclose(stdin);
    return 0;
}

最小k个数的更多相关文章

  1. 求n个数中的最大或最小k个数

    //求n个数中的最小k个数        public static void TestMin(int k, int n)        {            Random rd = new Ra ...

  2. nyoj 678 最小K个数之和

    最小K个数之和 时间限制:1000 ms  |  内存限制:65535 KB 难度:2   描述 输入n个整数,输出其中最小的K个数之和.例如输入4,5,1,1,6,2,7,3,3这9个数字,当k=4 ...

  3. 最小K个数之和

    描述 输入n个整数,输出其中最小的K个数之和.例如输入4,5,1,1,6,2,7,3,3这9个数字,当k=4,则输出最小的4个数之和为7(1,1,2,3). 输入 测试样例组数不超过10 每个测试案例 ...

  4. 算法试题 - 找出最小 k 个数

    题目 题目:输入n个整数,找出其中最小的K个数.例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,. 解析 思路1 这一题应用堆排序算法复杂度只有O(nlog k), ...

  5. 【13】堆排序 最小K个数

    题目 输入整数数组 arr ,找出其中最小的 k 个数.例如,输入4.5.1.6.2.7.3.8这8个数字,则最小的4个数字是1.2.3.4. 收获 优先队列实现 (n1,n2)->n2-n1是 ...

  6. 剑指Offer28 最小的K个数(Partition函数应用+大顶堆)

    包含了Partition函数的多种用法 以及大顶堆操作 /*********************************************************************** ...

  7. 找出最小的k个数

    •已知数组中的n个正数,找出其中最小的k个数. •例如(4.5.1.6.2.7.3.8),k=4,则最小的4个数是1,2,3,4 •要求: –高效: –分析时空效率 •扩展:能否设计出适合在海量数据中 ...

  8. 编程算法 - 最小的k个数 红黑树 代码(C++)

    最小的k个数 红黑树 代码(C++) 本文地址: http://blog.csdn.net/caroline_wendy 题目: 输入n个整数, 找出当中的最小k个数. 使用红黑树(multiset) ...

  9. 笔试算法题(03):最小第K个数 & 判定BST后序序列

    出题:输入N个整数,要求输出其中最小的K个数: 分析: 快速排序和最小堆都可以解决最小(大)K个数的问题(时间复杂度为O(NlogN)):另外可以建立大小为K的最大堆,将前K个数不断插入最大堆,对于之 ...

随机推荐

  1. 非常有用的css使用总结

    积小流以成江海,很多东西你不总结就不是你的东西 常用css总结: /*设置字体*/ @font-face { font-family: 'myFont'; src: url('../font/myFo ...

  2. Dice (II) (DP)唉,当时没做出来

    Dice (II) Time Limit: 3000MS   Memory Limit: 32768KB   64bit IO Format: %lld & %llu [Submit]   [ ...

  3. 详细分析apache httpd反向代理的用法

    html { font-family: sans-serif } body { margin: 0 } article,aside,details,figcaption,figure,footer,h ...

  4. 初学者易上手的SSH-struts2 01环境搭建

    首先,SSH不是一个框架,而是多个框架(struts+spring+hibernate)的集成,是目前较流行的一种Web应用程序开源集成框架,用于构建灵活.易于扩展的多层Web应用程序. 集成SSH框 ...

  5. Python 获取当前脚本文件路径目录

    # -*- coding: cp936 -*- import sys,os # 获取脚本文件的当前路径 def cur_file_dir(): # 获取脚本路径 path = sys.path[0] ...

  6. Java面向对象 IO (四)

     Java面向对象  IO  (四) 知识概要:                 (1)打印流 (2)序列流 SequenceInputStream (3)ObjectInputStream与Ob ...

  7. C#微信公众号/订阅号开发 接口源码

    using System; using System.Web; using System.IO; using System.Text; using System.Web.Security; using ...

  8. SQL SERVER 查看日志大小及日志已满的处理方法 (转)

    --解决方法 --日志文件满而造成SQL数据库无法写入文件时,可用两种方法: --查看数据库日志大小 dbcc sqlperf(logspace) --清空日志. --1.打开查询分析器,输入命令 D ...

  9. Spring MVC 过滤静态资源访问

    过滤的必要性 一般来说,HTTP 请求都会被映射到 DispatcherServlet,进而由具体的类来承接处理,但对于类似 js 或者 css 这样的静态资源则没必要这样,因为对资源的获取只需返回资 ...

  10. PHP+nginx 线上服务研究(一)

    一. 基本介绍 OpenResty® 是一个基于Nginx和Lua的高性能Web平台,其内部集成了大量精良的Lua库.第三方模块以及大多数的依赖项.用于方便搭建能够处理超高并发.扩展性极高的动态Web ...