转载并参考July的博客http://topic.youkuaiyun.com/u/20101126/10/b4f12a00-6280-492f-b785-cb6835a63dc9.html,万分感谢!
题目:
腾讯面试题--给你10分钟时间,根据上排给出十个数,求在其下排填出对应的十个数,要求下排每个数都是先前上排那十个数在下排出现的次数。
上排的十个数如下:
【0,1,2,3,4,5,6,7,8,9】
初看此题,貌似很难,10分钟过去了,可能有的人,题目都还没看懂。
举一个例子,
数值: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次....
以此类推.
/*Title: 6.求上排数字在下排出现的次数
Author: gocode
Date: 2012-10-04*/
#include <iostream>
using namespace std;
#define len 10
// 定义求解的类NumberTB
class NumberTB
{
private:
int bottom[len]; // 下排数字数组
bool success;
public:
NumberTB();
int round;
int top[len]; // 上排数字数组
int* getBottom();
void setNextBottom();
int getFrequency(int num);
};
// 构造函数
NumberTB::NumberTB()
{
success = false;
for(int i = 0; i < len; i++)
top[i] = i;
}
// 求下排数字
int* NumberTB::getBottom()
{
round = 0;
while(!success)
{
round++;
setNextBottom();
}
return bottom;
}
void NumberTB::setNextBottom()
{
bool reB = true;
for(int i = 0; i < len; i++)
{
int frequency = getFrequency(i);
if(bottom[i] != frequency)
{
bottom[i] = frequency;
reB = false;
}
}
success = reB;
}
int NumberTB::getFrequency(int num)
{
int count = 0;
for(int i = 0; i < len; i++)
{
if(bottom[i] == num)
count++;
}
return count;
}
int main()
{
NumberTB nTB;
int* up = nTB.top;
for(int j = 0; j< len; j++) // 打印上排数组
cout<<*up++<<" ";
cout<<endl;
int* result = nTB.getBottom();
for(int i = 0; i < len; i++) // 打印下排数组
cout<<*result++<<" ";
cout<<endl;
cout<<"Run round: "<<nTB.round<<endl;
getchar();
return 0;
}
结果:
