Leetcode860
题目描述:
在柠檬水摊上,每一杯柠檬水的售价为 5
美元。顾客排队购买你的产品,(按账单 bills
支付的顺序)一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5
美元、10
美元或 20
美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5
美元。
注意,一开始你手头没有任何零钱。
给你一个整数数组 bills
,其中 bills[i]
是第 i
位顾客付的账。如果你能给每位顾客正确找零,返回 true
,否则返回 false
。
代码及注释:
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int f[15]={0};
//开始做生意
for(int i=0;i<bills.size();i++){
//收您5块
if(bills[i]==5){
f[5]++;
}
//收你10块,我必须有5块钱才能做你的生意
else if(bills[i]==10){
//不然做不了
if(f[5]==0)return false;
f[5]--;
f[10]++;
}
//收你20,1.我有10块和5块,2.我有3张5块
else{
if(f[10]!=0){
if(f[5]==0)return false;
f[5]--;f[10]--;
}else if(f[5]>=3){
f[5]-=3;
}else return false;
}
}
return true;
}
};
Leetcode452:
题目描述:
有一些球形气球贴在一堵用 XY 平面表示的墙面上。墙面上的气球记录在整数数组 points
,其中points[i] = [xstart, xend]
表示水平直径在 xstart
和 xend
之间的气球。你不知道气球的确切 y 坐标。
一支弓箭可以沿着 x 轴从不同点 完全垂直 地射出。在坐标 x
处射出一支箭,若有一个气球的直径的开始和结束坐标为 x
start
,x
end
, 且满足 xstart ≤ x ≤ x
end
,则该气球会被 引爆 。可以射出的弓箭的数量 没有限制 。 弓箭一旦被射出之后,可以无限地前进。
给你一个数组 points
,返回引爆所有气球所必须射出的 最小 弓箭数 。
代码及注释:
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
//按照左边界来排序
sort(points.begin(),points.end(),[](vector<int>&s1,vector<int>&s2){
return s1[0]<s2[0];
});
//射出箭的总数
int sum=0;
for(int i=0;i<points.size();){
//发射
sum++;
int j=i+1;
//当前箭可以射爆气球的区间范围
int left=points[i][0];
int right=points[i][1];
//找下一个气球看看,是否在此区间
while(j<points.size()&&points[j][0]<=right){
//如果可以射爆下一个,则跟新这跟箭区间范围
left=points[j][0];
if(right>=points[j][1])right=points[j][1];
j++;
}
i=j;
}
return sum;
}
};
Leetcode406:
题目描述:
假设有打乱顺序的一群人站成一个队列,数组 people
表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki]
表示第 i
个人的身高为 hi
,前面 正好 有 ki
个身高大于或等于 hi
的人。
请你重新构造并返回输入数组 people
所表示的队列。返回的队列应该格式化为数组 queue
,其中 queue[j] = [hj, kj]
是队列中第 j
个人的属性(queue[0]
是排在队列前面的人)。
代码及注释:
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
int n = people.size();
vector<vector<int>> ans;
// 按身高降序、k值升序排序
sort(people.begin(), people.end(), [](const vector<int>& s1, const vector<int>& s2) {
if (s1[0] != s2[0]) return s1[0] > s2[0];
else return s1[1] < s2[1];
});
//开始排队!!!
for (int i = 0; i < n; i++) {
//这个人要插入到哪里去捏
int pos = people[i][1];
ans.insert(ans.begin() + pos, people[i]);
}
return ans;
}
};