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

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://blog.chinaunix.net/uid-26602509-id-3669465.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: