605.种花问题
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int size = flowerbed.size();
int cnt = 0;
flowerbed.insert(flowerbed.begin(),0);
flowerbed.insert(flowerbed.end(),0);//在两边插入0使特殊情况不特殊
for(int i = 0;i < size;i++)
if(!flowerbed[i] && !flowerbed[i + 1] && !flowerbed[i + 2]){
cnt++;
i += 1;
if(i == size)
break;
}
if(cnt >= n)
return 1;
else
return 0;
}
};
需要注意 001 和 100 的两种边界情况
452.用最少数量的箭引爆气球
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
sort(points.begin(),points.end());
if(points.empty())
return 0;
int size = points.size();
int cnt = 0;
int pre = points[0][1];
for(int i = 1;i < size;i++)
if(points[i][0] <= pre){
cnt++;
pre = min(points[i][1],pre);//只记录相同区间的最小值
}
else
pre = points[i][1];
return size - cnt;
}
};
763.划分字母区间
class Solution {
public:
vector<int> partitionLabels(string S) {
int N = S.size();
vector<int> ends(26, -1);
for (int i = 0; i < N; ++i) {
ends[S[i] - 'a'] = i;
}
vector<int> res;
int i = 0;
while (i < N) {
int r = ends[S[i] - 'a'];
for (int j = i + 1; j <= r; ++j) {
r = max(r, ends[S[j] - 'a']);
}
res.push_back(r - i + 1);
i = r + 1;
}
return res
}
};
用map的思想记录每个字母最后出现的位置,然后再次遍历求区间解
注意删减答案ans的区间
122.买股票的最佳时机
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum = 0;
for(int i = 0;i < prices.size() - 1;i++)
if(prices[i] < prices[i + 1])
sum += prices[i + 1] - prices[i];
return sum;
}
};
今天比昨天高,有盈利就可以进行一次卖出操作,然后将所有利润加和就是答案