考完了,也找到了实习。准备去上海巨人网络了~然后就是紧张的实习生活以及准备秋招。
所以开始回到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);
}