剑指offer-最小的k个数

题目描述

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

解题思路

借鉴快速排序中分治的思想,首先调用Partition函数找到分治点下标m,若m与k相等,则位于m之前的m个数即为解;若m小于k,则继续在m右边找分治点;若m大于k,则继续在m左边找分治点,直到m与k相等。

代码

 1 class Solution {
 2 public:
 3     vector<int> GetLeastNumbers_Solution(vector<int> &input, int k) {
 4         vector<int> v;
 5         int l=input.size();
 6         if(input.empty()||k<1||k>l)
 7             return v;
 8         if(k==l)
 9             return input;
10         int m=Partition(input,0,l-1);
11         while(m!=k){
12             if(m<k)
13                 m=Partition(input,m+1,l-1);
14             else
15                 m=Partition(input,0,m-1);
16         }
17         for(int i=0;i<m;i++)
18             v.push_back(input[i]);
19         return v;
20     }
21     int Partition(vector<int> &a, int f, int l) {
22         int i = f - 1;
23         for (int j = f; j < l; j++)
24         {
25             if (a[j] <= a[l]) {
26                 i++;
27                 swap(a[i], a[j]);
28             }
29         }
30         i++;
31         swap(a[i], a[l]);
32         return i;
33     }
34 };

猜你喜欢

转载自www.cnblogs.com/wmx24/p/8889313.html