leetcode第352场周赛补题

6909. 最长奇偶子数组 - 力扣(LeetCode)

思路:模拟

class Solution {
public:
    int longestAlternatingSubarray(vector& nums, int threshold) {
        int res = 0;
        int n = nums.size();
        for(int i = 0; i < n; i ++ )
        {
            if(nums[i] % 2 == 0 && nums[i] <= threshold)
            {
                for(int j = i + 1; j < n; j ++ )
                {
                    if(nums[j] % 2 == nums[j - 1] % 2 || nums[j] > threshold) break;
                    res = max(res, j - i + 1);
                }
            }
        }
        if(res == 0)
        {
            for(int i = 0; i < n; i ++ ) if(nums[i] % 2 == 0 && nums[i] <= threshold) return 1;
        }
        return res;
    }
};

6916. 和等于目标值的质数对 - 力扣(LeetCode)

思路:线性筛质数预处理出n以内的质数,然后双指针模拟

class Solution {
public:
    vector> findPrimePairs(int n) {
        vector> res;
        
        int primes[1000010], cnt = 0;
        bool st[1000010];
        memset(primes, -1, sizeof primes);
        memset(st, false, sizeof st);
        for(int i = 2; i <= n; i ++ )
        {
            if(!st[i]) primes[cnt ++ ] = i;
            for(int j = 0; primes[j] <= n / i; j ++ )
            {
                st[primes[j] * i] = true;
                if(i % primes[j] == 0) break;
            }
        }
        
        int l = 0, r = cnt - 1;
        while (l <= r)
        {
            if(primes[l] + primes[r] > n) r -- ;
            else if(primes[l] + primes[r] < n) l ++ ;
            else
            {
                res.push_back({primes[l], primes[r]});
                l ++ , r -- ;
            }
        }
        
        return res;
    }
};

6911. 不间断子数组 - 力扣(LeetCode)

思路:用multiset来维护滑动窗口,比赛中没想到,自己暴力+剪枝过不了最后几个

class Solution {
public:
    long long continuousSubarrays(vector& nums) {
        int n = nums.size();
        long long res = 0;
        multiset s;
        
        for(int i = 0, j = 0; i < n; i ++ )
        {
            s.insert(nums[i]);
            while (j <= i && *s.rbegin() - *s.begin() > 2)
            {
                s.erase(s.find(nums[j]));
                j ++ ;
            }
            res += (long long)i - j + 1;
        }

        return res;
    }
};

2763. 所有子数组中不平衡数字之和 - 力扣(LeetCode)

思路:枚举,计算不平衡贡献值

class Solution {
public:
    int sumImbalanceNumbers(vector& nums) {
        int res = 0, n = nums.size();
        bool st[n + 2];
        for(int i = 0; i < n; i ++ )
        {
            int cnt = 0;
            memset(st, false, sizeof st);
            st[nums[i]] = true;
            for(int j = i + 1; j < n; j ++ )
            {
                int x = nums[j];
                if(!st[x])
                {
                    cnt += 1 - st[x - 1] - st[x + 1];
                    st[x] = true;
                }
                res += cnt;
            }
        }
        return res;
    }
};

你可能感兴趣的:(数据结构,c++,算法)