周赛补题。

力扣84双周:

第二题:https://leetcode.cn/problems/count-number-of-bad-pairs/

遍历一次数组,统计差值的数量,可以求得"好数对"的数量。(差值相同的组合都是好数对)

由总量减去"好数对"的数量的即为坏数对的数量。

class Solution {
public:
    long long countBadPairs(vector<int>& nums) {
        long long sum = 0, n = nums.size();
        map<int, int>mp;
        for(int i = 0; i < n; i++) {
            mp[i - nums[i]]++;
        }
        for(map<int, int>::iterator it = mp.begin(); it != mp.end(); it++) {
            sum += (long long)it->second * (long long)(it->second - 1) / 2;
        }
        return n * (n - 1) / 2 - sum;
    }
};

力扣305:

第一题:https://leetcode.cn/problems/number-of-arithmetic-triplets/

用一个 unordered_set 记录出现过的数,然后枚举 nums[i],检查 nums[i] - diff 与 nums[i] + diff 是否都在 unordered_set 里即可。因为数组严格递增,因此若 nums[i] - diff 出现过,那么下标一定比 i 小;同理若 nums[i] + diff 出现过,那么下标一定比 i 大。所以无需担心下标大小的限制。

class Solution {
public:
    int arithmeticTriplets(vector<int>& nums, int diff) {
        int n = nums.size();
        unordered_set<int> st;
        for (int x : nums) st.insert(x);
        
        int ans = 0;
        for (int i = 0; i < n; i++) if (st.count(nums[i] - diff) > 0 && st.count(nums[i] + diff) > 0) ans++;
        return ans;
    }
};

acwing63:

第二题:https://www.acwing.com/problem/content/4507/

若 nn 为奇数,先手必赢;若 nn 为偶数,先手必输,利用单链表频繁的去消除字符串中的元素,最后统计出所有两个连续且相同的字母的数量。看奇偶即可。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <list>

using namespace std;

list<char> lp;

int main()
{
    string str;
    cin >> str;

    int n = str.length();

    int cnt = 0;
    char last = '#';
    for (int i = 0; i < n; i ++ ) 
    {
        if (last != str[i]) 
        {
            last = str[i];
            lp.push_back(last);
        }
        else 
        {
            cnt ++ ;
            lp.pop_back();
            last = lp.back();
        }
    }

    if (cnt == 0) puts("No");
    else 
    {
        if (cnt % 2) puts("Yes");
        else puts("No");
    }
    return 0;
}

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值