1. 程式人生 > >2012百度實習生面試題一道,打亂100個數的順序,越亂越好 .

2012百度實習生面試題一道,打亂100個數的順序,越亂越好 .

題目如下:

一個數組中有0-99共100個數,要求在在O(n)的時間內打亂這個陣列的順序,越亂越好。

我的思路如下:

設定一個bound值(最初bound值為99),每次迴圈,隨機生成一個數組下標tmpIndex=rand()%bound,交換a[bound]和a[tmpIndex];

每次迭代後,bound值減小1,直到減小到bound指向第一個元素位置。這也就是為什麼要用while(Bound >= 1)

[cpp] view plaincopyprint?
  1. #include <iostream>   
  2. #include <cmath> 
      
  3. #include <cstdlib>   
  4. using namespace std;  
  5. void swap(int & a, int & b)  
  6. {  
  7.     if(a == b)  
  8.         return;  
  9.     int tmp = a;  
  10.     a = b;  
  11.     b = tmp;  
  12. }  
  13. int main()  
  14. {  
  15.     srand(time(0));  
  16.     int a[100];  
  17.     for(int i=0; i<100; i++)  
  18.         a[i] = i;  
  19.     int highBound = 99, tmpIndex;  
  20.     while(highBound >= 1)  
  21.     {  
  22.         tmpIndex = rand() % highBound;  
  23.         swap(a[tmpIndex], a[highBound]);  
  24.         highBound--;  
  25.     }  
  26.     for(int i=0; i<100; i++)  
  27.         cout << a[i] << " " ;  
  28.     cout << endl;  
  29.     return 0;  
  30. }  

執行結果如下:


轉自:http://blog.chinaunix.net/uid-26602509-id-3669465.html