剑指offer 例题

it2025-07-16  4

题目: 实现一个排序算法,排序对象是本公司员工的年龄。要求时间复杂度O(n),空间复杂度不能超过O(n)。

#include<iostream> using namespace std; void SortAge(int Ages[],int length) { if (NULL == Ages || length <= 0) return; const int oldAge = 99; int timesOfAge[oldAge+1]; for (int i = 0; i <= oldAge; i++) timesOfAge[i] = 0; for (int j = 0; j < length;j++) { int age = Ages[j]; if (age>oldAge || age < 0) throw exception("Invalid Value!"); timesOfAge[age]++; } int index = 0; for (int k = 0; k <= oldAge; k++) { for (int s = 0; s < timesOfAge[k]; s++) { Ages[index] = k; index++; } } } int main() { int Age[] = { 1, 5, 45, 56, 8, 6, 78, 5, 2, 4, 6, 23, 66, 65, 26, 23 }; SortAge(Age,16); for (size_t i = 0; i < 16; i++) { cout << Age[i] << " "; } return 0; }

转载于:https://www.cnblogs.com/bhlsheji/p/5057004.html

相关资源:剑指offer例题(Java编程通过).pptx
最新回复(0)