【LeetCode刷题笔记:1833.雪糕的最大数量】

28 篇文章 0 订阅

考完了,也找到了实习。准备去上海巨人网络了~然后就是紧张的实习生活以及准备秋招。

所以开始回到LeetCode当常驻选手了。
题目:
在这里插入图片描述
今天这题如果不使用计数排序法的话,其实就是简单题。只需要简单排序一下数组,然后采用贪心的思路来计算得到最终的结果。

(为了复习一下算法,排序并未使用sort,自己重写了一次快排,但是会有一个非常极端的测试用例会超时,所以提交的时候还是用的Sort)

代码(C++版本)

#include<iostream>
#include<vector>
#include<algorithm> 

using namespace std;

class Solution {
public:
    int maxIceCream(vector<int>& costs, int coins) {
//    	sort(costs.begin(),costs.end());
        QuickSort(costs,0,costs.size()-1);

		for(auto& elem:costs)
		{
			cout<<elem<<" ";
		}
		cout<<endl;
		
        int count = 0;
        
        int i = 0;
        while(i<costs.size()&&coins >= costs[i])
        {
        	coins -= costs[i];
            count++;
            i++;
        }

        return count;
    }
    
    void QuickSort(vector<int>& costs,int left,int right)
    {
    	if(left>=right)
    	{
    		return;
		}
		int i = left;
		int j = right;
		int key = costs[left];
		
		while(i<j)
		{
			while(i<j&&key<=costs[j])
			{
				j--;
			}
			
			if(i<j) costs[i] = costs[j];
			
			while(i<j&&key>=costs[i])
			{
				i++;
			}
			
			if(i<j) costs[j] = costs[i];
		}
		
		costs[i] = key;
		QuickSort(costs,left,i-1);
		QuickSort(costs,i+1,right);
	}
};

int main()
{
	vector<int> costs = {7,3,3,6,6,6,10,5,9,2};
	int coins = 56;
	Solution solution;
	cout<<solution.maxIceCream(costs,coins); 
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值