134. 加油站
在一条环路上有 n 个加油站,其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。
给定两个整数数组 gas 和 cost ,如果你可以按顺序绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1 。如果存在解,则 保证 它是 唯一 的。
题目链接:LeetCode134.加油站
文档讲解:代码随想录LeetCode134.加油站
题解
依次遍历标号 i 对应的油量和消耗量,计算累计的剩余量,当累计剩余量为负数时,说明需要从 i+1 开始绕行;如果总的累计剩余量为负数,说明油量不足以支撑绕行所有加油站。
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int curSum = 0;
int totalSum = 0;
int start = 0;
for (int i = 0; i < gas.size(); i++) {
curSum += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
if (curSum < 0) {
start = i + 1;
curSum = 0;
}
}
if (totalSum < 0)
return -1;
return start;
}
};
- 时间复杂度:O(nlogn)
- 空间复杂度:O(1)
135. 分发糖果
n 个孩子站成一排。给你一个整数数组 ratings 表示每个孩子的评分。
你需要按照以下要求,给这些孩子分发糖果:
- 每个孩子至少分配到 1 个糖果。
- 相邻两个孩子评分更高的孩子会获得更多的糖果。
请你给每个孩子分发糖果,计算并返回需要准备的 最少糖果数目 。
题目链接:LeetCode135.分发糖果
文档讲解:代码随想录LeetCode135.分发糖果
题解
先考虑一个方向:局部最优:只要右边评分比左边大,右边的孩子就多一个糖果,全局最优:相邻的孩子中,评分高的右边孩子获得比左边孩子更多的糖果。再考虑反方向进行遍历。
class Solution {
public:
int candy(vector<int>& ratings) {
if (ratings.size() == 1)
return 1;
vector<int> candyVec(ratings.size(), 1);
for (int i = 0; i <= ratings.size() - 2; i++) {
if (ratings[i] < ratings[i + 1]) {
candyVec[i + 1] = candyVec[i] + 1;
}
}
for (int j = ratings.size() - 1; j >= 1; j--) {
if (ratings[j - 1] > ratings[j]) {
candyVec[j - 1] = max(candyVec[j - 1], candyVec[j] + 1);
}
}
return accumulate(candyVec.begin(), candyVec.end(), 0);
}
};
- 时间复杂度:O(n)
- 空间复杂度:O(n)
860. 柠檬水找零
在柠檬水摊上,每一杯柠檬水的售价为 5 美元。顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
注意,一开始你手头没有任何零钱。
给你一个整数数组 bills ,其中 bills[i] 是第 i 位顾客付的账。如果你能给每位顾客正确找零,返回 true ,否则返回 false 。
题目链接:LeetCode860.柠檬水找零
文档讲解:代码随想录LeetCode860.柠檬水找零
题解
模拟找零的过程,十元只能找五元,二十元可以找10+5或者5+5+5.
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
vector<int> rest(3, 0);
for (int i = 0; i < bills.size(); i++) {
if (bills[i] == 5) {
rest[0]++;
}
if (bills[i] == 10) {
if (rest[0] > 0) {
rest[0]--;
rest[1]++;
} else
return false;
}
if (bills[i] == 20) {
if (rest[0] > 0 && rest[1] > 0) {
rest[0]--;
rest[1]--;
rest[2]++;
} else if (rest[0] >= 3) {
rest[0] -= 3;
rest[2]++;
} else
return false;
}
}
return true;
}
};
- 时间复杂度:O(n)
- 空间复杂度:O(1)
406. 根据身高重建队列
假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki] 表示第 i 个人的身高为 hi ,前面 正好 有 ki 个身高大于或等于 hi 的人。
请你重新构造并返回输入数组 people 所表示的队列。返回的队列应该格式化为数组 queue ,其中 queue[j] = [hj, kj] 是队列中第 j 个人的属性(queue[0] 是排在队列前面的人)。
题解
先按照身高 hi 进行排序,再根据比 hi 高的数据量 ki 插入合适的位置。
class Solution {
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];
}
public:
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 position = people[i][1];
res.insert(res.begin() + position, people[i]);
}
return res;
}
};
- 时间复杂度:O(nlogn + n^2)
- 空间复杂度:O(1)