笔试题之 三色球

笔试题之三色球

个人信息:就读于燕大本科软件工程专业 目前大三;

本人博客:google搜索“cqs_2012”即可;

个人爱好:酷爱数据结构和算法,希望将来搞科研为人民作出自己的贡献;

博客内容:笔试题之三色球;

博客时间:2014-4-2

编程语言:C++

编程坏境:Windows

编程工具:vs2008

  • 引言

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

  • 题目

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

  • 思路

首先题目有个条件,条件很严格,我们做题时先不考虑条件限制,先思考自己的理解与想法。

我们可以排序,然后在输出; 但是题目有要求,我们就不能在原地排序了,可以复制信息,然后再处理副本

如果不排序有什么方法呢?我想到的是哈希表,根据球的颜色作为关键字建立哈希表,然后顺序输出哈希表就可以了,有点像xml文本中对关键字建立倒排的感觉

举个例子如下

hash-table

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

  • 实验

程序解释

第一步输出 实验数据 球号和球颜色

第二步建立 hash table

第三步输出 hash table

  • 代码

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;
		}
	}
}


 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值