除了剑指offer上面的这种问题的解决方法以外,这里给出了另一种解决问题的方法,其实还有其他的方法如利用最大堆等来解决该问题
1.有一组N个数,确定其中第K个最大者
该问题的第一个解法 就是将N个数读进一个数组中,再通过某种排序算法(如快速排序等)以递减顺序将数组排序,然后返回位置K上的元素。
该方法的第二种解法 就是先把前K个元素读入数组(以递减的顺序)对其排序。接着,将剩下的元素再逐个读入。当新元素被读到时,如果它小于数组中的第K个元素,则忽略;否则将其放在数组中正确的位置上,同时将数组中的一个元素挤出数组。当算法终止时,位于第K个位置上的元素作为结果返回。具体实现如下:
#include<iostream>
using namespace std;
#define K 4
#define N 10
int main(void)
{
int a[N];
int i,j,m;
cout<<"enter the first K elementsof the array a:"<<endl;//按降序输入
for(i=0;i<K;i++)
cin>>a[i];
cout<<endl;
for(i=K;i<N;i++)
{
cout<<"enter the a["<<i<<"]:";
cin>>a[i];
if(a[i]<a[K-1])
{
//cout<<"stop do and continue!"<<endl;
continue;
}
else
{
//cout<<"do and continue!"<<endl;
for(j=0;j<K;j++)
{
if(a[i]>=a[j])
break;
}
for(m=K-1;m>=j+1;m--)
{
a[m]=a[m-1];
}
a[j]=a[i];
}
}
cout<<"the target element is:"<<a[K-1]<<endl;
//for(i=0;i<K;i++)
// cout<<a[i]<<endl;
return 0;
}
2.有一组N个数,求最小的k个数
思路与上面相同,代码如下:
//Name:jae
//purpose:有一组数,求其中的最小的K个数,从小到大排序
#include<iostream>
using namespace std;
#define K 4
#define N 10
void Bubble_sort(int a[],int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1] )
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
int main(void)
{
int a[N];
int i,j,m;
cout<<"enter the first K elementsof the array a:"<<endl;
for(i=0;i<K;i++)
cin>>a[i];
//对a[i]从小到大排序
Bubble_sort(a,K);
cout<<endl;
for(i=K;i<N;i++)
{
cout<<"enter the a["<<i<<"]:";
cin>>a[i];
if(a[i]>=a[K-1])
{
//cout<<"stop do and continue!"<<endl;
continue;
}
else
{
//cout<<"do and continue!"<<endl;
for(j=0;j<K;j++)
{
if(a[i]<a[j])
break;
}
for(m=K-1;m>=j+1;m--)
{
a[m]=a[m-1];
}
a[j]=a[i];
}
}
//cout<<"the target element is:"<<a[K-1]<<endl;
for(i=0;i<K;i++)
cout<<a[i]<<endl;
cout<<endl;
return 0;
}