题目

输入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. NOIP2017SummerTraining0706

    个人感受:这套题也依旧在划水,和wqh在一起,然后也没怎么好好想,第一题开始时打了个思维很好的方法,但是事完全错误的:然后就开始第二题,然后第二题枚举20分,然后看答案多了25分,就拿了 45分:第三 ...

  2. Keyboard Row

    Given a List of words, return the words that can be typed using letters of alphabet on only one row' ...

  3. javascript的数值转换 number()详解

    ---恢复内容开始--- number() parseInt() parseFloat()这三个函都可以把数非数值转换为数值,我们看看他们的区别在哪里 一 Number() 转型函数Number()是 ...

  4. 配置和启动Kubernetes服务

    安装etcd服务 下载安装包 wget https://github.com/coreos/etcd/releases/download/v3.1.3/etcd-v3.1.3-linux-amd64. ...

  5. Python系列之反射、面向对象

    一.反射 说反射之前先介绍一下__import__方法,这个和import导入模块的另一种方式 1. import commons 2. __import__('commons') 如果是多层导入: ...

  6. Window window = Window.GetWindow(控件)

    Window window = Window.GetWindow(控件)

  7. Elasticsearch学习笔记 一

    本文版权归博客园和作者吴双本人共同所有 转载和爬虫请注明原文地址 www.cnblogs.com/tdws. 本文参考和学习资料 <ES权威指南> 一.基本概念 存储数据到ES中的行为叫做 ...

  8. 线性布局(LinearLayout)

    线性布局(LinearLayout) 备注 match_parent填充布局单元内尽可能多的空间 wrap_content完整显示控件内容 orientation有两个值,horizontal水平显示 ...

  9. TCP/IP四层模型与OSI参考模型

    TCP/IP四层模型: 1.链路层(数据链路层/网络接口层):包括操作系统中的设备驱动程序.计算机中对应的网络接口卡 2.网络层(互联网层):处理分组在网络中的活动,比如分组的选路. 3.运输层:主要 ...

  10. android6.0 SerialPort 服务

    上一篇博客描述了一个简单的串口应用程序和驱动程序,了解了应用程序访问串口的基本操作,如打开串口,设置串口,写串口,读串口,关闭串口等.和Linux串口驱动的基本框架.这里将了解Android下的串口系 ...