题目1371:最小的K个数-九度

题目描述:
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
输入:
每个测试案例包括2行:
第一行为2个整数n,k(1<=n,k<=200000),表示数组的长度。
第二行包含n个整数,表示这n个数,数组中的数的范围是[0,1000 000 000]。
输出:
对应每个测试案例,输出最小的k个数,并按从小到大顺序打印。
样例输入:
8 4
4 5 1 6 2 7 3 8
样例输出:

1 2 3 4

推荐指数:※※

来源:http://ac.jobdu.com/problem.php?pid=1371

快速排序的前k个结果。注意,当pivot的值大于k时,从(j+1,high)之间的数就不需要处理了。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
#define LL long long
void swap(LL *a, LL *b){
	LL tmp=*a;
	*a=*b;
	*b=tmp;
}

int partition_arr(int low,int high,LL *arr,const int k){
	if(low>=high)
		return 0;
	LL tmp=arr[low];
	int i=low,j=high+1;
    LL pivot=arr[low];
	while(1){
        while(arr[++i]<pivot);
        while(arr[--j]>pivot);
        if(i<j)
            swap(arr[i],arr[j]);
        else 
            break;
        
	}
    swap(arr[low],arr[j]);
    if(low<j-1) partition_arr(low,j-1,arr,k);
    if(j+1<high&&j+1<=k) partition_arr(j+1,high,arr,k);
	return 0;
}
int main()
{
	int n,k,i;
	while(~scanf("%d%d",&n,&k)){
		LL *arr=new LL [n];
		for(i=0;i<n;i++)
			scanf("%lld",&arr[i]);
        partition_arr(0,n-1,arr,k-1);
		if(n>=k){
            printf("%d",arr[0]);
			for(i=1;i<k;i++)
				printf(" %lld",arr[i]);
            printf("\n");
		}
	}
	return 0;
}

使用最大堆

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
#define LL long long
void swap(LL *a, LL *b){
	LL tmp=*a;
	*a=*b;
	*b=tmp;
}
struct  cmp{
    bool operator()(LL a,LL b){
        return a<b;
    }
};
void find_k(LL *arr,int len,int k,priority_queue<LL,vector<LL>,cmp> *heap){
   int i;
   for(i=0;i<len;i++){
        if((*heap).size()>=k){
            if((*heap).top()>arr[i]){
                (*heap).pop();
                (*heap).push(arr[i]);
            }
        }
        else
                (*heap).push(arr[i]);

   }
}
void print_heap(priority_queue<LL,vector<LL>,cmp> *heap){ 
    stack<LL> s;
    while(!(*heap).empty()){
        s.push((*heap).top());
        (*heap).pop();
    }
    if(!s.empty()){
        printf("%lld",s.top());
        s.pop();
        while(!s.empty()){
            printf(" %lld",s.top());
            s.pop();
        }
    }
}
int main()
{
	int n,k,i;
	while(~scanf("%d%d",&n,&k)){
		LL *arr=new LL [n];
		for(i=0;i<n;i++)
			scanf("%lld",&arr[i]);
		if(n>=k){
            priority_queue<LL,vector<LL>,cmp> heap;
            find_k(arr,n,k,&heap);
            print_heap(&heap);
            printf("\n");
		}
	}
	return 0;
}



你可能感兴趣的:(题目1371:最小的K个数-九度)