Leetcode 860.柠檬水找零
题目链接:860.柠檬水找零
解题思路:思路就是将零钱存进来,然后如果没有零钱的话则return false;足够找零的话则return true;
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int cnt_5 = 0, cnt_10 = 0, cnt_20 = 0;
int resume;
for(int i = 0; i < bills.size(); i++) {
resume = bills[i] - 5;
if(resume == 0) {
cnt_5 ++;
}
else if(resume == 5) {
cnt_5 --;
if(cnt_5 < 0) return false;
cnt_10 ++;
} else if(resume == 15) {
if(cnt_10 == 0) {
cnt_5 -= 3;
} else {
cnt_10 --;
cnt_5 --;
}
if(cnt_5 < 0 || cnt_10 < 0) return false;
cnt_20 ++;
}
}
return true;
}
};
- 时间复杂度为O(n)
- 空间复杂度为O(1)
Leetcode 406.根据身高重建队列
题目链接:406.根据身高重建队列
解题思路:先排序一个维度(身高),再排序第二个维度(前面有多少个人大于等于当前身高),然后再遍历一遍,将每个人插入队列中。position就是自己的k。
class Solution {
public:
static bool cmp(vector<int> &A, vector<int> &B) {
if(A[0] == B[0]) return A[1] < B[1];
return A[0] > B[0];
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
vector<vector<int>> queue;
sort(people.begin(), people.end(), cmp);
for(int i = 0; i < people.size(); i++) {
int position = people[i][1];
queue.insert(queue.begin() + position, people[i]);
}
return queue;
}
};
- 时间复杂度为O(nlogn + n ^ 2)
- 空间复杂度为O(n)
Leetcode 452.用最少数量的箭引爆气球
题目链接:452.用最少数量的箭引爆气球
解题思路:贪心思路就是射区间重叠最多的气球;那么就需要先排序;并且在循环中,只有当i的左区间比i-1的右区间大了才+1,同时一直要min区间的右边界,这样才能最大化射区间重叠最多的气球
class Solution {
public:
static bool cmp(vector<int> &A, vector<int> &B) {
return A[0] < B[0];
}
int findMinArrowShots(vector<vector<int>>& points) {
if(points.size() == 0) return 0;
int res = 1;
sort(points.begin(), points.end(), cmp);
for(int i = 1; i < points.size(); i++) {
if(points[i][0] > points[i-1][1]) {
res++;
} else {
points[i][1] = min(points[i-1][1], points[i][1]);
}
}
return res;
}
};
- 时间复杂度为O(nlogn)
- 空间复杂度为O(1)