uacs2024

导航

leetcode 2099. 找到和最大的长度为 K 的子序列

2099. 找到和最大的长度为 K 的子序列

特别注意,题目要求不改变原来的元素顺序

我的代码

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]);//pair可以直接这样添加
        }
        // 按照数值降序排序,这里使用了Lambda表达式。如果不使用Lambda表达式,要自定义一个返回值为bool的比较函数fun。然后sort(nums.begin(),nums.end(),fun);
        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;
    }
};

 

posted on 2024-11-27 22:02  ᶜʸᵃⁿ  阅读(23)  评论(0)    收藏  举报