LeetCode第336场周赛

2023.3.12LeetCode第336场周赛

A. 统计范围内的元音字符串数

思路

直接模拟

代码

class Solution {
public:
    bool check(char c ) {
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
            return true;
        return false;
    }
    
    int vowelStrings(vector<string>& words, int left, int right) {
        int ans = 0;
        for (int i = left; i <= right; i ++ ) {
            if (check(words[i].back()) && check(words[i][0]))
                ans ++ ;
        }
        return ans;
    }
};

B. 重排数组以得到最大前缀分数

思路

要使前缀和大于0的数量尽量多,可以把数组从大到小排序,然后计算前缀和大于0的个数

代码

class Solution {
public:
    int maxScore(vector<int>& nums) {
        sort(nums.begin(), nums.end(), [&](int a, int b) {
            return a > b;
        });
        long long sum = 0;
        int ans = 0;
        for (int x : nums) {
            sum += x;
            if (sum > 0) ans ++ ;
        }
        return ans;
    }
};

C. 统计美丽子数组数目

思路

题目要求的美丽子数组条件可以转化为数组的异或和为0
由于a ^ a = 0
记录所有前缀异或和,遍历所有元素找到异或和相等的数量,累计即可

代码

class Solution {
public:
    typedef long long ll;
    
    long long beautifulSubarrays(vector<int>& nums) {
        int n = nums.size();
        unordered_map<int, int> mp;
        mp[0] ++ ;
        ll ans = 0;
        for (int i = 0, s = 0; i < n; i ++ ) {
            s ^= nums[i];
            ans += mp[s];
            mp[s] ++ ;
        }
        return ans;
    }
};

D. 完成所有任务的最少时间

思路

从小到大枚举所有时间点是否必选
尽量不选当前点,如果剩余点的数量不能满足则必选

代码

class Solution {
public:
    int findMinimumTime(vector<vector<int>>& tasks) {
        int m = 0;
        for (auto x : tasks)
            m = max(m, x[1]);
        int ans = 0;
        for (int i = 1; i <= m; i ++ ) {
            bool f = false; //判断当前时间点是否必选
            for (auto& x : tasks) {
                if (i >= x[0] && i <= x[1] && (x[1] - i < x[2])) { //剩余点不能满足时必选
                    f = true;
                    break;
                }
            }
            if (f) { //要选当前时间点
                ans ++ ;
                for (auto& x : tasks) {
                    if (i >= x[0] && i <= x[1] && x[2] > 0) //减去包含当前点的
                        x[2] -- ;
                }
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值