题目:某公司有几万名员工,请完成一个时间复杂度为O(n)的算法对该公司员工的年龄作排序,可使用O(1)的辅助空间。
看到这题,我就开始蒙头想,一个小时过去了,还是不知道。只能看答案了:
void SortAges(int ages[], int length)
{
if(ages== NULL || length <= 0)
return;
const int oldestAge = 99;
int timesOfAge[oldestAge+ 1];
for(int i = 0; i <=oldestAge; ++ i)
timesOfAge[i] = 0;
for(int i = 0; i < length;++ i)
{
int age = ages[i];
if(age< 0 || age > oldestAge)
throw new std::exception("ageout of range.");
++ timesOfAge[age];
}
int index = 0;
for(int i = 0; i <=oldestAge; ++ i)
{
for(int j = 0; j <timesOfAge[i]; ++ j)
{
ages[index] = i;
++ index;
}
}
}
在上面的代码中,允许的范围是0到99岁。数组timesOfAge用来统计每个年龄出现的次数。某个年龄出现了多少次,就在数组ages里设置几次该年龄。这样就相当于给数组ages排序了。该方法用长度100的整数数组辅助空间换来了O(n)的时间效率。由于不管对多少人的年龄作排序,辅助数组的长度是固定的100个整数,因此它的空间复杂度是个常数,即O(1)。