您的位置:首页 > 职场人生

笔试题之 三色球

2014-04-02 16:33 239 查看

笔试题之三色球

个人信息:就读于燕大本科软件工程专业 目前大三;
本人博客:google搜索“cqs_2012”即可;
个人爱好:酷爱数据结构和算法,希望将来搞科研为人民作出自己的贡献;
博客内容:笔试题之三色球;
博客时间:2014-4-2
编程语言:C++
编程坏境:Windows
编程工具:vs2008

[align=left]引言[/align]

不骄不躁,简简单单,安安静静,思考再思考

[align=left]题目[/align]

三色球排序的问题,相同的球放到一起,让你按顺序输出红白蓝三种颜色的球,可以用012来表示,要求只能扫描一次数组

[align=left]思路[/align]

首先题目有个条件,条件很严格,我们做题时先不考虑条件限制,先思考自己的理解与想法。
我们可以排序,然后在输出; 但是题目有要求,我们就不能在原地排序了,可以复制信息,然后再处理副本
如果不排序有什么方法呢?我想到的是哈希表,根据球的颜色作为关键字建立哈希表,然后顺序输出哈希表就可以了,有点像xml文本中对关键字建立倒排的感觉
举个例子如下



hash-table



然后顺序输出 hash-table 即可。

[align=left]实验[/align]



程序解释
第一步输出 实验数据 球号和球颜色
第二步建立 hash table
第三步输出 hash table

[align=left]代码[/align]

test.cpp
// head file
#include<iostream>
#include<vector>
#include<map>
using namespace std;

// function: ball_with_three_colors
// input: a array of ball and its length, and all the colors length
// output: sorted balls id
// 功能: 给一堆球按颜色排序,然后输出
void ball_with_three_colors(int *balls,int length,int colors_length);

// function: main
int main()
{
int * balls = new int[10];
cout<<"data follows"<<endl;
for(int i =0;i<10;i++)
{
balls[i] = rand()%3 + 1;
cout<<"ball-id:  "<<i<<"    ball-color:    "<<balls[i]<<endl;
}
ball_with_three_colors(balls,10,3);
system("pause");
return 0;
}

// function: ball_with_three_colors
// input: a array of ball and its length, and all the colors length
// output: sorted balls id
// 功能: 给一堆球按颜色排序,然后输出
void ball_with_three_colors(int *balls,int length,int colors_length)
{
if(balls == NULL || length <= 0)
{
cout<<"exception of function ball_with_three_colors input"<<endl;
}
else
{
vector<int> * hash_ball = new vector<int>[colors_length];

for( int i = 0; i<length; i++ )
{
if(balls[i] <= length && balls[i] > 0)
hash_ball[ balls[i] - 1 ].insert(hash_ball[ balls[i] - 1 ].end(),i);
else
{
cout<<"colors input error"<<endl;
break;
}
}
cout<<"球排序后,球号如下"<<endl;
for(int i=1;i<=colors_length;i++)
{
for(vector<int>::iterator it = hash_ball[i-1].begin(); it<hash_ball[i-1].end(); it++)
{
cout<<(*it)<<" ";
}
cout<<endl;
}
}
}


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试题