29.最小的K个数——剑指offer

题目描述

输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
 1 class Solution {//快速排序nlogn
 2 private:
 3    int Partion(vector<int> &input,int low,int high)
 4     {
 5         int i = low;
 6         int j = high;
 7         int temp = input[low];
 8         while(i < j)
 9         {
10             while(i < j && temp <= input[j]) --j;
11             input[i] = input[j];
12             while(i < j && temp >= input[i]) ++i;
13             input[j] = input[i];
14         }
15         input[i] = temp;
16         return i;
17     }
18    void quicksort(vector<int> &input ,int low , int high)
19     {
20         if(low < high)
21         {
22             int pivot = Partion(input, low , high);
23             quicksort(input, low, pivot -1);
24             quicksort(input, pivot + 1, high);
25         }
26     }
27 public:
28     vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
29         int l = input.size();
30         vector<int> res;
31         if(l < k) return res;
32         quicksort(input, 0 , l - 1);
33         for(int i = 0; i < k; ++i)
34         {
35             res.push_back(input[i]);
36         }
37         return res;
38     }
39 };

 

 1 class Solution {//堆排序时间复杂度nlogk
 2 private:
 3  void heapsort(vector<int> &input , int k)
 4   {
 5       for(int i = k/2 - 1; i >= 0; --i)
 6       {
 7           int j = 2*i + 1; //左结点
 8           while(j < k)
 9           {
10               if(j < k - 1 &&input[j + 1] > input[j]) j++;
11               if(input[i] >= input[j]) break;
12               else swap(input[j], input[i]);
13           }
14       }
15   }
16 public:
17     vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
18         int n = input.size();
19         vector<int> res;
20         if(n < k) return res;
21         heapsort(input, k);
22         for(int i = k; i < n; ++i)
23         {
24             if(input[i] < input[0]) 
25             {
26                 swap(input[0], input[i]);
27                 heapsort(input, k);
28             }
29         }
30         for(int i = 0; i < k; ++i)
31         {
32             res.push_back(input[i]);
33         }
34         return res;
35     }
36 };

 

posted @ 2019-05-23 22:11  unique_ptr  阅读(87)  评论(0编辑  收藏  举报