159.库存管理(TOPk问题!)

159.库存管理(TOPk问题!)_第1张图片

思路:也是tok的问题,与上篇博客思路一样,只不过是求前k个小的元素!

基于快排分块思路的代码如下:

class Solution {
public:
    int getkey(vector&nums,int left,int right)
    {
        int r=rand();
        return nums[r%(right-left+1)+left];
    }
    void qsort(vector&nums,int left,int right,int k)
    {
        if(left>=right ) return ;
        vectorret(k);
        int l=-1,r=right+1;
        int i=0;
        int key=getkey(nums,left,right);
        while(ikey)
            {
                swap(nums[--r],nums[i]);
            }
            else
            {
                i++;
            }
        }

        int a=l-left+1;
        int b=r-l-1;
        int c=right-r+1;

        if(a>=k)
        {
            return qsort(nums,left,l,k);
        }
        else if(a+b>=k)
        {
            return ;
        }
        else
        {
            return qsort(nums,r,right,k-a-b);
        }
        return ;
    }

    vector inventoryManagement(vector& stock, int cnt) 
    {
        int n=stock.size();
        qsort(stock,0,n-1,cnt);
        return {stock.begin(),stock.begin()+cnt};
    }
};

 优先级队列代码:

class Solution {
public:
    vector inventoryManagement(vector& stock, int cnt)
    {
        vectorret(cnt);
        priority_queue,greater>q;
        for(auto ch:stock)
        {
            q.push(ch);
        }
        for(int i=0;i

你可能感兴趣的:(算法,leetcode,数据结构,学习方法,c++)