题解
【基础】字典排序
1 条题解
-
0
解题思路
把数字当作字符串比较,字符串比较顺序就是题目要求的字典顺序。
参考代码
// 先读入题目给出的数据。 // 再按照题目要求进行计算。 // 最后按规定格式输出答案。 #include <iostream> #include <string> using namespace std; int main() { int n; string a[10]; cin >> n; // 把整数按字符串读入,才能比较字典顺序。 for (int i = 0; i < n; i++) cin >> a[i]; // 字符串比较会先比较前面的字符,正好符合题目要求。 for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] > a[j]) { string t = a[i]; a[i] = a[j]; a[j] = t; } for (int i = 0; i < n; i++) cout << a[i] << (i + 1 == n ? '\n' : ' '); return 0; }复杂度分析
排序需要 O(n^2) 时间;其余循环按照实际遍历次数计算。代码使用固定大小数组,额外空间复杂度为 O(1) 或 O(n)。
- 1