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;
}
};
note:
在当前油的总量为负数时,选择下一个站点重新开始。我感觉这个思路和最大子序和很像。。
2.分发糖果
代码:
class Solution {
public:
int candy(vector<int>& ratings) {
int result = 0;
vector<int> candy(ratings.size(),1);
// 从左向右遍历 处理右孩子比左边的孩子得分高的情况
for(int i = 1; i < ratings.size(); i++){
if(ratings[i] > ratings[i - 1]){
candy[i] = candy[i - 1] + 1;
}
}
// 从右向左遍历 处理左孩子比右边的孩子得分高的情况
for(int i = ratings.size() - 2; i >= 0; i--){
if(ratings[i] > ratings[i + 1]){
candy[i] = max(candy[i + 1] + 1, candy[i]);
}
}
// 求和
for(int a : candy){
result += a;
}
return result;
}
};
note:
首先是要满足两个条件的时候,分开来考虑,不要想着一次性全部解决,容易顾此失彼。
其次是,这道题的遍历顺序也有讲究,在进行糖果数的计算时,要起到一个累计的效果,因此从左往右遍历是来计算右孩子比左孩子分数高的情况,从右往左遍历是来计算左孩子比右孩子分数高的情况。
以及,第二次遍历时,要和第一次的结果进行比较,取一个最值。
3.柠檬水找零
代码:
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0;
int ten = 0;
for(int i = 0; i < bills.size(); i++){
if(bills[i] == 5){
five++;
}else if(bills[i] == 10){
if(five > 0){
five--;
ten++;
}else{
return false;
}
}else if(bills[i] == 20){
if(ten > 0 && five > 0){
ten--;
five--;
}else if(five >= 3){
five -= 3;
}else{
return false;
}
}
}
return true;
}
};
note:
这道题起始不难,就是模拟找零的过程就好了。如果没有对应的零钱可以找,就return false跳出循环即可。
4.根据身高重建队列
代码:
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];
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(),people.end(),cmp); // 按升高从高到低进行排序
vector<vector<int>> que;
// 按照身高排序之后,优先按身高高的people的k来插入,后序插入节点也不会影响前面已经插入的节点,最终按照k的规则完成了队列。
for(int i = 0; i < people.size(); i++){
int position = people[i][1];
que.insert(que.begin() + position,people[i]);
}
return que;
}
};
note:按照身高排序之后,优先按身高高的people的k来插入,后序插入节点也不会影响前面已经插入的节点,最终按照k的规则完成了队列。