数组排序的常规做法就是定义个比较函数然后传进排序函数: #include <algorithm> #include <iostream> #include <vector> using namespace std; int main(int argc, char* argv[]) { vector<int> nums = {2, 3, 5, 7, 11, 13, 15, 17}; sort(nums.begin(), nums.end(), [](int x, int y) { int units_x = x % 10; int units_y = y % 10; if (units_x == units_y) return x < y; return units_x < units_y; }); for (int x : nums) cout << x << " "; cout << endl; return 0; }不过这里个位数的值只有0-9一共10种,所以像楼上一样分到10个vector中排序,然后依次汇总应该才是题目想要的做法,毕竟给定的数组是有序的,这个条件在之前的代码里没利用: #include <assert.h> #include <algorithm> #include <array> #include <iostream> #include <vector> using namespace std; int main(int argc, char* argv[]) { // nums为有序数组 vector<int> nums = {2, 3, 5, 7, 11, 13, 15, 17}; array<vector<int>, 10> buckets; // TODO: use array<forward_list, 10> may be better? for (int x : nums) buckets[x % 10].emplace_back(x); size_t index = 0; for (const auto& v : buckets) { for (int x : v) { assert(index < nums.size()); nums[index++] = x; } } for (int x : nums) cout << x << " "; cout << endl; return 0; }
点赞 11

相关推荐

2025-12-26 00:57
门头沟学院 golang
菜菜_带带:作弊的前提是你得有真东西,不然很容易就备看出来了,至于混进去,都是面试造火箭,工作拧螺丝罢了
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务