目录
前言
LeetCode134. 加油站
LeetCode135. 分发糖果
LeetCode860.柠檬水找零
LeetCode406.根据身高重建队列
一、LeetCode134. 加油站
题目链接:
代码:
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;
}
};
二、LeetCode135. 分发糖果
题目链接:
代码:
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candy(ratings.size(), 1);
for(int i = 1; i < candy.size(); i++)
{
if(ratings[i] > ratings[i - 1])
{
candy[i] = candy[i - 1] + 1;
}
}
for(int i = candy.size() - 2; i >= 0; i--)
{
if(ratings[i] > ratings[i + 1])
{
candy[i] = max(candy[i], candy[i + 1] + 1);
}
}
int sum = 0;
for(int num:candy)
{
sum += num;
}
return sum;
}
};
三、LeetCode860.柠檬水找零
题目链接:
代码:
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
int five=0,ten=0;
for(auto&bill:bills){
if(bill==5){
five++;
}
else if(bill==10){
ten++;
five--;
}
else{
if(five>0&&ten>0){
five--;
ten--;
}
else{
five-=3;
}
}
if(five<0||ten<0){
return false;
}
}
return true;
}
};
四、LeetCode406.根据身高重建队列
题目链接:
代码:
bool compare(vector<int>& left, vector<int>& right)
{
if(left[0] > right[0])
{
return true;
}
else if(left[0] == right[0] && left[1] <= right[1])
{
return true;
}
return false;
}
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(), people.end(), compare);
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;
}
};