2012百度实习生面试题一道,打乱100个数的顺序,越乱越好 .
2015-05-04 22:08
267 查看
题目如下:
一个数组中有0-99共100个数,要求在在O(n)的时间内打乱这个数组的顺序,越乱越好。
我的思路如下:
设置一个bound值(最初bound值为99),每次循环,随机生成一个数组下标tmpIndex=rand()%bound,交换a[bound]和a[tmpIndex];
每次迭代后,bound值减小1,直到减小到bound指向第一个元素位置。这也就是为什么要用while(Bound >= 1)
[cpp] view
plaincopyprint?
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
void swap(int & a, int & b)
{
if(a == b)
return;
int tmp = a;
a = b;
b = tmp;
}
int main()
{
srand(time(0));
int a[100];
for(int i=0; i<100; i++)
a[i] = i;
int highBound = 99, tmpIndex;
while(highBound >= 1)
{
tmpIndex = rand() % highBound;
swap(a[tmpIndex], a[highBound]);
highBound--;
}
for(int i=0; i<100; i++)
cout << a[i] << " " ;
cout << endl;
return 0;
}
执行结果如下:
![](http://my.csdn.net/uploads/201205/11/1336701404_9055.jpg)
转自:http://blog.chinaunix.net/uid-26602509-id-3669465.html
一个数组中有0-99共100个数,要求在在O(n)的时间内打乱这个数组的顺序,越乱越好。
我的思路如下:
设置一个bound值(最初bound值为99),每次循环,随机生成一个数组下标tmpIndex=rand()%bound,交换a[bound]和a[tmpIndex];
每次迭代后,bound值减小1,直到减小到bound指向第一个元素位置。这也就是为什么要用while(Bound >= 1)
[cpp] view
plaincopyprint?
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
void swap(int & a, int & b)
{
if(a == b)
return;
int tmp = a;
a = b;
b = tmp;
}
int main()
{
srand(time(0));
int a[100];
for(int i=0; i<100; i++)
a[i] = i;
int highBound = 99, tmpIndex;
while(highBound >= 1)
{
tmpIndex = rand() % highBound;
swap(a[tmpIndex], a[highBound]);
highBound--;
}
for(int i=0; i<100; i++)
cout << a[i] << " " ;
cout << endl;
return 0;
}
执行结果如下:
![](http://my.csdn.net/uploads/201205/11/1336701404_9055.jpg)
转自:http://blog.chinaunix.net/uid-26602509-id-3669465.html
相关文章推荐
- 2012百度实习生面试题一道,打乱100个数的顺序,越乱越好
- 2012百度实习生招聘面试题
- 2012百度实习生招聘面试题
- 2012百度实习生招聘面试题
- 2012百度实习生招聘面试题
- 2012 百度实习生面试题
- 面试经之一道淘汰85%面试者的百度开发者面试题
- 2014百度实习生面试题(部分)详解
- 百度实习生面试题-按行读取文件
- 百度面试题,一天一道慢慢来
- 腾讯2012实习生招聘面试题:矩阵中A移动到B一共有多少走法
- 2012百度实习生笔试
- 一道淘汰85%面试者的百度开发者面试题
- 一道关于try,finally执行顺序的面试题
- 一道异常处理执行顺序面试题的简单分析
- 多线程按顺序依次打印ABCD---java多线程的一道经典面试题
- 解一道百度面试题
- 百度面试题一道2(著名的蚂蚁问题)
- 一道让我无地自容的百度面试题
- 一道百度面试题