1 条题解
-
0
【例55.3】 绝对值排序
解题思路
以绝对值作为降序排序关键字,输出原数。使用long long保存输入确保负数绝对值安全。
正确性说明
按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。
易错点
保留负号,输出的不是绝对值本身。
复杂度
时间O(n log n),空间O(n)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<long long> a(n); for (auto &x : a) cin >> x; sort(a.begin(), a.end(), [](long long x, long long y) { return llabs(x) > llabs(y); }); for (int i = 0; i < n; i++) { if (i) cout << " "; cout << a[i]; } cout << "\n"; return 0; }
- 1