Leetcode 101刷题记录(2)

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;
    }
};

今天比昨天高,有盈利就可以进行一次卖出操作,然后将所有利润加和就是答案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值