当我们不用自己的头脑,就会放弃对命运的把握,而把它交给别人。我们必须把握生活,才不至浪费生活。
——摘自奥格.曼狄诺《羊皮卷》
第6 题
腾讯面试题:给你10 分钟时间,根据上排给出十个数,在其下排填出对应的十个数
要求下排每个数都是先前上排那十个数在下排出现的次数。
上排的十个数如下:
【0,1,2,3,4,5,6,7,8,9】
举一个例子,
数值: 0,1,2,3,4,5,6,7,8,9
分配: 6,2,1,0,0,0,1,0,0,0
0 在下排出现了6 次,1 在下排出现了2 次,
2 在下排出现了1 次,3 在下排出现了0 次....
*************************************************************************************************
1. 巧用C++类的构造函数,将两个数组赋初值;
并且,类的成员数据可以由函数随时访问,避免了普通变量的局限性;
( good job!!)
2. 依次计算数组1元素在数组2中出现的次数(frequence=getfrequence(top[i])),
只要有一个bottom[i]!=frequence,则success=false,
3. success=false,则必须重新开始新一轮的top与bottom比较,
直到top.与bottom全部元素一一对应;
*************************************************************************************************
#include <iostream>
using namespace std;
#define LEN 10
class NumberTB
{
private:
int top[LEN];
int bottom[LEN];
bool success;
public:
NumberTB();
int* getBottom();
void setNextBottom();
int getFrequecy(int num);
};
NumberTB::NumberTB() /*上,下排初始化*/
{
success = false;
for(int i=0;i<LEN;i++)
{
top[i] = i;
bottom[i]=0;
}
}
int* NumberTB::getBottom()
/*只有连续的两次getnextbottom所有元素都不变才最终结束,若有一个bottom数组元素改变,则继续*/
{
while(!success)
{
setNextBottom();
}
return bottom;
}
void NumberTB::setNextBottom()
{
bool reB = true;
for(int i=0;i<LEN;i++)
{
int frequecy = getFrequecy(top[i]);
/*若是不等说明还不是最终结果,success=false;*/
if(bottom[i] != frequecy)
{
bottom[i] = frequecy;
reB = false;
}
}
success = reB;
}
/*此处的num 即指要查找上排的数i(0~9)在数组bottom中出现次数*/
int NumberTB::getFrequecy(int num)
{
int count = 0; /*count作为计数器*/
for(int i=0;i<LEN;i++)
{
if(bottom[i] == num)
{
count++;
}
}
return count;
}
int main()
{
NumberTB nTB;
int* result= nTB.getBottom();
for(int i=0;i<LEN;i++,result++)
{
cout<<*result<<endl;
}
return 0;
}