zoukankan      html  css  js  c++  java
  • 剑指offer:最小k个数

    题目描述

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

    代码:

    1.普通人的大顶堆解法

    class Solution {
    public:
        vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
            if (k == 0 || k > input.size()) return {};
            priority_queue<int> p;
            vector<int> ans;
            for(int i = 0; i < k; i++){
                p.push(input[i]);
            }
            for(int i = k; i < input.size(); i++){
                if(input[i] < p.top()){
                    p.pop();
                    p.push(input[i]);
                }
            }
            for(int i = 0; i < k; i++){
                ans.push_back(p.top());
                p.pop();
            }
            return ans;
            
        }
    };

    2.

    普通人懒人解法

    class Solution {
    public:
        vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
            if(k > input.size() || input.empty()) return {};
            vector<int> ans;
            sort(input.begin(), input.end());
            for(int i = 0; i < k; i++){
                ans.push_back(input[i]);
            }
            
            return ans;
        }
    };

    3.

    冒泡排序:

    class Solution {
    public:
        vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
            if(k > input.size() || input.empty()) return {};
            vector<int> ans;
            for(int i = 0; i < k; i++){
                for(int j = 0; j < input.size()-i - 1; j++){
                    if(input[j] < input[j+1]){
                        int tmp = input[j];
                        input[j] = input[j+1];
                        input[j+1] = tmp;
                    }
                }
                ans.push_back(input[input.size()-i-1]);
            }
            
            return ans;
        }
    };
  • 相关阅读:
    Impala服务JVM崩溃问题
    Impala编译部署-6集群部署
    Impala编译部署-5单机部署-2
    Impala编译部署-5单机部署-1
    Impala编译部署-4
    Impala编译部署-3
    Impala编译部署-2
    Impala编译部署-1
    工作转向Kudu
    python 屏幕录制改进版,无opencv黑框显示
  • 原文地址:https://www.cnblogs.com/BillowJ/p/12730962.html
Copyright © 2011-2022 走看看