2012百度實習生面試題一道,打亂100個數的順序,越亂越好 .
阿新 • • 發佈:2019-01-07
題目如下:
一個數組中有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