面試100題-2

本題目轉自博客http://zhedahht.blog.163.com/blog/static/25411174201131184017844/

完全出於加強算法能力的單純目的。

 

完整的題目描述:

某公司有幾萬名員工,請完成一個時間複雜度是O(n)的算法對該公司員工的年齡做排序,

可以使用O(1)的輔助空間

 

思路:1.從要求的時間複雜度上看應該是穩定排序

      2.員工的年齡一般集中在20-60歲之間分佈,可以考慮分段排序再歸併,但是不符合O(n)

      3.處理的數據比較大,常見的手段比如位運算,計數數組等

      4.對於輔助空間爲O(1)的理解

 

開始的代碼:(只寫功能實現部分)

  1. void SortAge(int employeesum, int *employee) { 
  2.  
  3.      
  4.     int length = 70; 
  5.     int *employee_age_num = new int[length]; 
  6.  
  7.     //First,initialize the array 
  8.  
  9.     for(int i = 0; i< length; i++) 
  10.  
  11.         employee_age_num[i] = 0; 
  12.   
  13.  
  14.     //Scan the employees age information and record it 
  15.  
  16.     for(int i = 0; i < employeesum; i++)  
  17.  
  18.         employee_age_num[employee[i].age - 20]++; 
  19.   
  20.  
  21.     //Sort the employee array by the record information  
  22.  
  23.     int employee_index = 0; 
  24.  
  25.     for(int i = 0 ; i < length; i++) 
  26.  
  27.         for(int j = 0; j < employee_age_num[j]; j++) { 
  28.  
  29.             //.....Swap the employee information including age and other things 
  30.  
  31.             employee_index++;    
  32.  
  33.         } 
  34.  
  35.     delete []emplyee_age; 
  36.  

 

分析:上面的代碼寫的比較失敗,原因在於沒有弄清楚題目的意思

      1.對公司員工的 年齡 排序,而不是說對整個員工信息排序,二者在空間上要求不同

        以至於頭腦中構建的是員工信息可能是一個結構,需要對整體信息排序。

      2.使用O(1)的輔助空間,開始理解爲只能申請一個大小是1的空間,但是O(1)的意思是

        空間大小是常數,不隨N的變化而變化,這裏的1表示常量,

      3.對參數沒有進行異常情況處理,有的變量應該設置爲const,代碼的健壯性考慮不夠。

 

修改後的代碼:

這裏的employee數組存放的只是員工的年齡。

 

  1. bool SortAge(int employeesum, int *employee) { 
  2.      
  3.  
  4.     if(employee == NULL || employeesum <= 0) 
  5.  
  6.         return false
  7.          
  8.  
  9.     const int length = 70; 
  10.  
  11.     int *employee_age_num = new int[length]; 
  12.  
  13.  
  14.     //First,initialize the array 
  15.  
  16.     for(int i = 0; i< length; i++) 
  17.  
  18.         employee_age_num[i] = 0; 
  19.   
  20.  
  21.     //Scan the employees age information and record it 
  22.  
  23.     for(int i = 0; i < employeesum; i++)  
  24.  
  25.         employee_age_num[employee[i] - 20]++; 
  26.  
  27.      
  28.  
  29.     //Sort the employee array by the record information  
  30.  
  31.     int employee_index = 0; 
  32.  
  33.     for(int i = 0 ; i < length; i++) 
  34.  
  35.         for(int j = 0; j < employee_age_num[j]; j++) { 
  36.  
  37.             employee[employee_index] = i; 
  38.  
  39.             employee_index++;    
  40.  
  41.         } 
  42.  
  43.     delete []emplyee_age; 
  44.  
  45.     return true
  46.  

 

擴展:如果是根據員工的年齡,對整個員工的信息進行排序呢?

     (就是將代碼中employee[employee_index] = i;這句換成和對應位置的員工信息整體交換,

       但是正如flyinghearts所說,需要N個標誌位標記元素是否被訪問過,排序也就不穩定了)

總結:1.面試題目要看清楚,不一樣的條件限制,解決的方法也是不一樣的。

      2.代碼應該是先實現功能在逐步優化,但是不要因此就忘了邊界條件的檢測。

      3.功力還是太淺,急需加強學習。

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章