首页 > 代码库 > 数组中最小的K个数

数组中最小的K个数

思路:1、排序,取前k个元素;O(NlogN);2、分治,O(n),利用快排的思想;3、用set 维护最小的k个数,O(NlogK),可处理海量数据。

#include <iostream>
using namespace std;

void print(int *a,int n){
    if(a==NULL || n<=0 ) return;
    for(int i=0;i<n;i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

int Partition(int *a,int left,int right){
    int p=a[left];
    int l=left;
    int r=right;
    while(l<r){
        while( l<r && a[r]>=p) r--;
        if(l<r){
            a[l]=a[r];
            l++;
        }
        while( l<r && a[l]<=p) l++;
        if(l<r){
            a[r]=a[l];
            r--;
        }
    }
    a[l]=p;
    return l;
}

void quick_sort(int *a,int left,int right){
    if(left>=right) return;
    int p=Partition(a,left,right);
    quick_sort(a,left,p-1);
    quick_sort(a,p+1,right);
}

void leastKnum(int *a,int left,int right,int k){
    if(left>=right) return;
    int l=left;
    int r=right;
    int p=Partition(a,left,right);
    while(p!=k-1){
        if(p>k-1){
            r=p-1;
            p=Partition(a,l,r);
        }
        else{
            l=p+1;
            p=Partition(a,l,r);
        }
    }
    for(int i=0;i<k;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

int main(){
    int a[10]={2,7,8,3,5,4,9,0,1,6};
    print(a,10);
    leastKnum(a,0,9,4);
    //quick_sort(a,0,5);
    //print(a,6);
    return 0;
}