一、134 加油站

class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start = 0;
int cursum = 0;
int totalsum = 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;
}
};
二、135 分发糖果

class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candyVec(ratings.size(), 1);//保存ratings.size个1
int i;
int result = 0;
//右>左
for(i = 1;i<ratings.size();i++){//从第二个元素开始
if(ratings[i]>ratings[i-1]){
candyVec[i] = candyVec[i-1]+1;
}
}
//左>右
for(i = ratings.size()-2;i>=0;i--){//从倒数第二个元素开始
if(ratings[i]>ratings[i+1]){
candyVec[i] = max(candyVec[i+1]+1,candyVec[i]);//取两种情况都满足的值
}
}
for(i = 0;i<candyVec.size();i++){
result += candyVec[i];
}
return result;
}
};
三、860 柠檬水找零

class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five = 0;
int ten = 0;
int twenty = 0;
for(int bill:bills){
if(bill == 5)
five++;
if(bill == 10){
if(five <= 0)
return false;
ten++;
five--;
}
if(bill == 20){
if(ten>0&&five>0){
ten--;
five--;
twenty++;
}
else if(ten<=0&&five>=3){
five -= 3;
twenty++;
}
else
return false;
}
}
return true;
}
};
四、406 根据身高重建队列

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);//按照身高从大到小,身高一样则按k从小到大排序
vector<vector<int>>queue;
for(int i = 0;i<people.size();i++){
int pos = people[i][1];
queue.insert(queue.begin()+pos,people[i]);
}
return queue;
}
};