提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、860柠檬水找零
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
vector<int> res = {0, 0, 0};
for (int bill: bills) {
if (bill == 5) {
res[0] ++;
}
else if (bill == 10) {
res[0] --;
res[1] ++;
}
else {
if (res[1] > 0) {
res[1] --;
res[0] --;
}
else {
res[0] -= 3;
}
res[2] ++;
}
for (int num: res) {
if (num < 0) return false;
}
}
return true;
}
};
用两个int存5、10就行
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0, ten = 0;
for (int bill: bills) {
if (bill == 5) {
five ++;
}
else if (bill == 10) {
if (five < 0) return false;
five --;
ten ++;
}
else {
if (ten > 0 && five > 0) {
ten --;
five --;
}
else if (five > 2) {
five -= 3;
}
else return false;
}
}
return true;
}
};
二、406根据身高重建队列
可以说是毫无思路。
两个维度都需要考虑的题,确定一个维度后再考虑另一个维度。
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) {
sort(people.begin(), people.end(), cmp);
vector<vector<int>> res;
for (int i = 0; i < people.size(); i ++) {
int pos = people[i][1];
res.insert(res.begin() + pos, people[i]);
}
return res;
}
};
用vector的时间复杂度是O(n^2)。vector的insert非常费时,原因是:C++中vector是一个动态数组,如果插入元素大于预先数组大小,vector会申请两倍于原先普通数组的大小,然后把数据拷贝到另一个更大的数组上。
可以用链表优化插入的复杂度。优化版:
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) {
sort(people.begin(), people.end(), cmp);
list<vector<int>> res;
for (int i = 0; i < people.size(); i ++) {
int pos = people[i][1];
auto it = res.begin();
while (pos --) {
it ++;
}
res.insert(it, people[i]);
}
return vector<vector<int>>(res.begin(), res.end());
}
};
三、452用最少数量的箭引爆气球
class Solution {
public:
//合并区间的思路
int findMinArrowShots(vector<vector<int>>& points) {
sort(points.begin(), points.end());
int start = points[0][0];
int end = points[0][1];
int res = 1;
for (int i = 1; i < points.size(); i ++) {
if (points[i][0] <= end) {
start = points[i][0];
end = min(end, points[i][1]);
}
else{
res ++;
start = points[i][0];
end = points[i][1];
}
}
return res;
}
};