剑指offer29:最小的k个数

1 题目描述

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

2 思路和方法,C++核心代码

2.1 sort()函数,vector<int> push_back(); nlog(n)

 1 class Solution {
 2 public:
 3     vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
 4         sort(input.begin(),input.end());
 5         vector<int> result;
 6         if(k>input.size())
 7             return result;
 8         for(int i = 0;i<k;i++){
 9             result.push_back(input[i]);
10         }
11         return result;
12     }
13 };
View Code

2.2 Partition分治O(n)

 1 class Solution {
 2 public:
 3     vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
 4         // 必须检查k的大小否则出错!!!
 5         if (input.size() == 0 || k > input.size() || k<=0) 
 6             return vector<int>();
 7        
 8         int start = 0;
 9         int end = input.size() -1;
10         int index = Partition(input,start,end);
11         while(index != k-1){
12             if(index < k-1){
13                 start = index + 1;  // k在index右边
14                 index = Partition(input,start,end);
15             }
16             else{
17                 end = index -1;     // k在index左边
18                 index = Partition(input,start,end);
19             }
20         }
21         vector<int> ret;
22         for (int i = 0; i < k; ++i) {
23             ret.push_back(input[i]);
24         }
25         return ret;
26     }
27 
28     int Partition(vector<int> &data, int start, int end){
29         if(start > end)
30             return start;
31 
32         int key = data[start];  // 取第一个值为参考值
33         while(start< end){
34             while(data[end] >= key && start < end) end--;
35             data[start] = data[end];
36             while(data[start] <= key && start<end) start++;
37             data[end] = data[start];
38         }
39         data[start] = key;
40         return start;
41     }
42 };
View Code

参考资料

https://blog.csdn.net/zjwreal/article/details/88608506

原文地址:https://www.cnblogs.com/wxwhnu/p/11415890.html