特别注意,题目要求不改变原来的元素顺序
我的代码
class Solution { public: vector<int> maxSubsequence(vector<int>& nums, int k) { vector<int> temp(nums); sort(temp.begin(),temp.end()); int size = temp.size(); for(int i = 0;i < size - k;i++){ int t = temp[i];//效率还是很低,比如几个相同的元素找到还要从头再找一遍 auto it = find(nums.begin(),nums.end(),t); nums.erase(it); } return nums; } };
题解代码
class Solution { public: vector<int> maxSubsequence(vector<int>& nums, int k) { int n = nums.size(); vector<pair<int, int>> vals; // 辅助数组 for (int i = 0; i < n; ++i) { vals.emplace_back(i, nums[i]); } // 按照数值降序排序 sort(vals.begin(), vals.end(), [&](auto x1, auto x2) { return x1.second > x2.second; }); // 取前 k 个并按照下标升序排序 sort(vals.begin(), vals.begin() + k); vector<int> res; // 目标子序列 for (int i = 0; i < k; ++i) { res.push_back(vals[i].second); } return res; } };
标签:begin,temp,nums,int,vals,vector,序列,2099,leetcode From: https://www.cnblogs.com/uacs2024/p/18573203