0
点赞
收藏
分享

微信扫一扫

【五月集训5.4】———贪心

舟海君 2022-05-04 阅读 33

请添加图片描述

☘前言☘

开更五月集训专题,由浅入深,深入浅出,飞向大厂!


全文目录


1221. 分割平衡字符串

1221. 分割平衡字符串

解题思路1

代码

class Solution {
public:
    int balancedStringSplit(string s) {
        int tmp = s[0] == 'R' ? 1 : -1, n = s.size(), ans = 0;
        for(int i = 1;i < n;++i){
            s[i] == 'R' ? ++tmp : --tmp;
            if(tmp == 0)    ++ans;
        }
        return ans;
    }
};  

注意的点

  1. 默认的长度至少为1,否则tmp就会出错哦。

1827. 最少操作使数组递增

1827. 最少操作使数组递增

解题思路1

代码

class Solution {
public:
    int minOperations(vector<int>& nums) {
        int n = nums.size(), ans = 0,now = nums[0];
        for(int i = 1;i <n ;++i)
            if(nums[i] <= now)
                ans += (now - nums[i] + 1), now += 1;
            else now = nums[i];

        return ans;
    }
};

注意的点

利用now这个临时变量记录上一次的值,不需要每次使用数组元素,会增加速度。

2144. 打折购买糖果的最小开销

2144. 打折购买糖果的最小开销

解题思路

代码

class Solution {
public:
    int minimumCost(vector<int>& cost) {
        sort(cost.begin(),cost.end());
        int n = cost.size(), now = 1,ans = cost[n-1];
        for(int i = n - 2;i >= 0;i--){
            now = (now + 1) % 3;
            if(now == 0)    ans -= cost[i];
            ans += cost[i];
        }
        return ans;
    }
};

注意的点

  1. 虽然是简单题,我还是希望能学到东西,比如内存的方式之类的,cache加快速度,但是终究内存还是内存 一定是没有寄存器快的,这里的临时变量可以使用寄存器。

1400. 构造 K 个回文字符串

1400. 构造 K 个回文字符串

解题思路

代码

class Solution {
public:
    bool canConstruct(string s, int k) {
        int n = s.size(), left = 0;
        vector<int> hash(26);
        for(auto ch : s)    ++hash[ch - 'a'];
        for(auto hashi : hash)  
            if(hashi & 1)   ++left;
        return k <= n && k >= left;
    }
};

注意的点

  1. 没啥

写在最后

我还是希望能从简单的题目得到一些东西。

举报

相关推荐

0 条评论