134. 加油站
代码:
方法一:
class Solution { //134. 加油站 //暴力解法 模拟一圈
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
for (int i = 0; i < cost.size(); i++) {
int rest = gas[i] - cost[i];
int index = (i + 1) % cost.size();
while (rest > 0 && index != i) {
rest += gas[index] - cost[index];
index = (index + 1) % cost.size();
}
if (rest >= 0 && index == i)return i;
}
return -1;
}
};
方法二:
class Solution { //134. 加油站 贪心算法 找局部最优,当前累加rest[j]的和curSum一旦小于0,起始位置至少要是j+1,因为从j开始一定不行 确定全局最优
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;
}
int main() {
vector<int> gas = { 1, 2, 3, 4, 5 };
vector<int> cost = { 3, 4, 5, 1, 2 };
Solution s;
int result = s.canCompleteCircuit(gas, cost);
cout << result << endl;
return 0;
}
135. 分发糖果
代码:
class Solution { //135. 分发糖果 先从前向后遍历,比较右边孩子评分比左边孩子评分高的情况 再从后向前遍历,比较左边孩子评分比右边孩子评分高的情况
public:
int candy(vector<int>& ratings) {
vector<int> nums(ratings.size(), 1);
//从前向后
for (int i = 1; i < ratings.size(); ++i) {
if (ratings[i] > ratings[i - 1]) {
nums[i] = nums[i - 1] + 1;
}
}
//从后向前
for (int i = ratings.size() - 2; i >= 0; --i) {
if (ratings[i] > ratings[i + 1]) {
nums[i] = max(nums[i], nums[i + 1] + 1);
}
}
int result = 0;
for (int i = 0; i < nums.size(); ++i) {
result += nums[i];
}
return result;
}
};
860. 柠檬水找零
代码:
class Solution { //860. 柠檬水找零 分情况 遇见5直接bill5++;遇见10,bill10++,bill5--;遇见20如果bill10>0,bill10--,bill5--,否则bill5-=3;最后判断bill5和bill10是否小于0,小于0就说明找不开,返回false
public:
bool lemonadeChange(vector<int>& bills) {
int bill5 = 0;
int bill10 = 0;
for (int i = 0; i < bills.size(); ++i) {
if (bills[i] == 5)bill5++;
if (bills[i] == 10){
bill10++;
bill5--;
}
if (bills[i] == 20) {
if (bill10 > 0) {
bill10--;
bill5--;
}
else bill5 -= 3;
}
if (bill5 < 0 || bill10 < 0)return false;
}
return true;
}
};
406. 根据身高重建队列
代码:
class Solution { //406. 根据身高重建队列 先按身高排序(从大到小),身高相同的按k从小到大排序,然后从身高高的开始,将k作为下标 重新插入
public:
class mySort{
public:
bool operator()(vector<int> const& first, vector<int> const& second) {
if (first[0] == second[0]) return first[1] < second[1];
return first[0] > second[0];
}
};
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(), people.end(), mySort());
vector<vector<int>> result;
vector<vector<int>>::iterator it;
for (int i = 0; i < people.size(); ++i) {
it = result.begin() + people[i][1];
result.insert(it, people[i]);
}
return result;
}
};
int main() {
vector<vector<int>> people = { { 7, 1 }, { 4, 4 }, { 7, 0 }, { 5, 0 }, { 6, 1 }, { 5, 2 } };
Solution s;
vector<vector<int>> result = s.reconstructQueue(people);
return 0;
}