贪心算法4
LeetCode 860 柠檬水找零 2023.11.28
bool lemonadeChange(vector<int>& bills) {
unordered_map<int, int> unmap;
for (int i = 0; i < bills.size(); i++)
{
if(bills[i] == 5)
unmap[5]++;
if(bills[i] == 10)
{
if(unmap[5] > 0)
{
unmap[5]--;
unmap[10]++;
}
else
return false;
}
if(bills[i] == 20)
{
if(unmap[10] > 0 && unmap[5] > 0)
{
unmap[10]--;
unmap[5]--;
}
else if(unmap[10] == 0 && unmap[5] >= 3)
unmap[5] -= 3;
else
return false;
}
}
return true;
}
LeetCode 406 根据身高重建队列 2023.11.28
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
for (int i = 0; i < people.size(); i++)
{
vector<int>& max = people[i];
for (int j = i; j < people.size(); j++)
{
if(people[j][0] > max[0])
{
vector<int> temp = people[j];
people[j] = max;
max = temp;
}
else if(people[j][0] == max[0])
{
if(max[1] > people[j][1])
{
vector<int> temp = people[j];
people[j] = max;
max = temp;
}
}
}
}
vector<vector<int>> que;
for (int i = 0; i < people.size(); i++)
{
int postion = people[i][1];
que.insert(que.begin() + postion, people[i]);
}
return que;
}
LeetCode 452 用最少数量的箭引爆气球 2023.11.28
class Solution {
public:
static bool cmp(const vector<int> &a, const vector<int> &b)
{
if(a[0] == b[0])
return a[1] < b[1];
return a[0] < b[0];
}
int findMinArrowShots(vector<vector<int>>& points) {
int result = 0;
sort(points.begin(), points.end(), cmp);
for (int i = 0; i < points.size(); i++)
{
int temp = 1;
int right = points[i][1];
while(i+temp < points.size() && right >= points[i+temp][0])
{
right = min(right, points[i+temp][1]);
temp++;
}
if(temp != 1)
i += (temp-1);
result++;
}
return result;
}
};