复习
class Solution {
public:
static bool cmp(int a, int b) {
return abs(a)>abs(b);
}
int largestSumAfterKNegations(vector<int>& nums, int k) {
sort(nums.begin(), nums.end(), cmp);
for(int i=0; i<nums.size(); ++i) {
if(k>0 && nums[i]<=0) {
nums[i] *= -1;
k--;
}
}
if(k%2!=0) {
nums[nums.size()-1] *= -1;
}
int result = 0;
for(int num:nums) {
result += num;
}
return result;
}
};
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int curLeave = 0; // 查找哪个站可以满足
int totalLeave = 0;
int startIndex = 0;
for(int i=0; i<gas.size(); ++i) {
curLeave += gas[i] - cost[i];
totalLeave += gas[i] - cost[i];
if(curLeave<0) {
startIndex = i+1;
curLeave = 0;
}
}
if(totalLeave<0) {
return -1;
}
return startIndex;
}
};
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candyVect(ratings.size(), 1);
// 右边比左边多
for(int i=1; i<ratings.size(); i++) {
if(ratings[i]>ratings[i-1]) {
candyVect[i] = candyVect[i-1]+1;
}
}
// 左边比右边多
for(int i=ratings.size()-2; i>=0; --i) {
if(ratings[i]>ratings[i+1]) {
candyVect[i] = max(candyVect[i], candyVect[i+1]+1);
}
}
int result = 0;
for(int num:candyVect) {
result += num;
}
return result;
}
};
想法:判断三种情况,20块钱的时候优先10块钱
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++;
}else if(bill==10) {
// 十块钱
five--;
ten++;
if(five<0) {
return false;
}
}else {
// 二十块钱
if(five>0 && ten>0) {
ten--;
five--;
}else if(five>=3) {
five -= 3;
twenty++;
}else {
return false;
}
}
}
return true;
}
};
想法:先按身高进行排序,排完以后,可以放心按照k来插入
class Solution {
public:
static bool cmp(vector<int>& a, 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) {
vector<vector<int>> ans;
// 身高排序
sort(people.begin(), people.end(), cmp);
// 数量插入
for(int i=0; i<people.size(); ++i) {
int position = people[i][1];
ans.insert(ans.begin()+position, people[i]);
}
return ans;
}
};