本題目轉自博客http://zhedahht.blog.163.com/blog/static/25411174201131184017844/
完全出於加強算法能力的單純目的。
完整的題目描述:
某公司有幾萬名員工,請完成一個時間複雜度是O(n)的算法對該公司員工的年齡做排序,
可以使用O(1)的輔助空間
思路:1.從要求的時間複雜度上看應該是穩定排序
2.員工的年齡一般集中在20-60歲之間分佈,可以考慮分段排序再歸併,但是不符合O(n)
3.處理的數據比較大,常見的手段比如位運算,計數數組等
4.對於輔助空間爲O(1)的理解
開始的代碼:(只寫功能實現部分)
- void SortAge(int employeesum, int *employee) {
- int length = 70;
- int *employee_age_num = new int[length];
- //First,initialize the array
- for(int i = 0; i< length; i++)
- employee_age_num[i] = 0;
- //Scan the employees age information and record it
- for(int i = 0; i < employeesum; i++)
- employee_age_num[employee[i].age - 20]++;
- //Sort the employee array by the record information
- int employee_index = 0;
- for(int i = 0 ; i < length; i++)
- for(int j = 0; j < employee_age_num[j]; j++) {
- //.....Swap the employee information including age and other things
- employee_index++;
- }
- delete []emplyee_age;
- }
分析:上面的代碼寫的比較失敗,原因在於沒有弄清楚題目的意思
1.對公司員工的 年齡 排序,而不是說對整個員工信息排序,二者在空間上要求不同
以至於頭腦中構建的是員工信息可能是一個結構,需要對整體信息排序。
2.使用O(1)的輔助空間,開始理解爲只能申請一個大小是1的空間,但是O(1)的意思是
空間大小是常數,不隨N的變化而變化,這裏的1表示常量,
3.對參數沒有進行異常情況處理,有的變量應該設置爲const,代碼的健壯性考慮不夠。
修改後的代碼:
這裏的employee數組存放的只是員工的年齡。
- bool SortAge(int employeesum, int *employee) {
- if(employee == NULL || employeesum <= 0)
- return false;
- const int length = 70;
- int *employee_age_num = new int[length];
- //First,initialize the array
- for(int i = 0; i< length; i++)
- employee_age_num[i] = 0;
- //Scan the employees age information and record it
- for(int i = 0; i < employeesum; i++)
- employee_age_num[employee[i] - 20]++;
- //Sort the employee array by the record information
- int employee_index = 0;
- for(int i = 0 ; i < length; i++)
- for(int j = 0; j < employee_age_num[j]; j++) {
- employee[employee_index] = i;
- employee_index++;
- }
- delete []emplyee_age;
- return true;
- }
擴展:如果是根據員工的年齡,對整個員工的信息進行排序呢?
(就是將代碼中employee[employee_index] = i;這句換成和對應位置的員工信息整體交換,
但是正如flyinghearts所說,需要N個標誌位標記元素是否被訪問過,排序也就不穩定了)
總結:1.面試題目要看清楚,不一樣的條件限制,解決的方法也是不一樣的。
2.代碼應該是先實現功能在逐步優化,但是不要因此就忘了邊界條件的檢測。
3.功力還是太淺,急需加強學習。