HOT100打卡—day9—【堆】—最新8.22(还有1题)

1 215. 数组中的第K个最大元素

215. 数组中的第K个最大元素

时间复杂度要O(n)所以用了hash,空间换时间,ac代码:

class Solution {
public:
    int a[20010];
    int findKthLargest(vector<int>& nums, int k) {
        // hash
        int min = INT_MAX;
        int max = INT_MIN;
        for(auto x : nums)
        {
            a[x + 10000]++;
            if(x+1e4 > max)max = x + 1e4;
            if(x+1e4 < min)min = x + 1e4;
        }
        int cnt = 0;
        for(int i = max ; i >= min; i--)
        {
            cnt += a[i];
            if(cnt >= k)
                return i-1e4;
        }
        return 0;
    }
};

看了题解,忘了一个叫快速选择的东西:

todo

2 347. 前 K 个高频元素

347. 前 K 个高频元素

这次我用了map 之后转成vector排序,其实可以优先队列排序,见我的sxl题解

class Solution {
public:
    static bool cmp(pair<int,int> a,pair<int,int> b)
    {
        return a.second > b.second;
    }
    vector<int> topKFrequent(vector<int>& nums, int k) {
        // map
        map<int,int> mp;
        for(auto u : nums)
            mp[u]++;
        vector<pair<int,int>> tmp(mp.begin(),mp.end());
        sort(tmp.begin(),tmp.end(),cmp);

        vector<int> ans;
        for(int i = 0; i < k; i++)
            ans.push_back(tmp[i].first);
        return ans;
    }
};

3 todo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值