目录
力扣第305场周赛
A.算术三元组数目
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int len=nums.size(),res=0;
for(int i=0;i<len;i++){
for(int j=i+1;j<len;j++){
for(int k=j+1;k<len;k++){
if((nums[j]-nums[i]==diff) && (nums[k]-nums[j]==diff)) res++;
}
}
}
return res;
}
};
我趣,这也太暴力了,但过了🤣
但其实,用哈希表可以更快解决
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
unordered_map<int,bool> dic;
int res=0;
for(int i=0;i<nums.size();i++){
dic[nums[i]]=1;
if(dic[nums[i]-diff]&&dic[nums[i]-2*diff]){
res++;
}
}
return res;
}
};
B.受限条件下可到达节点的数目
从0节点开始进行BFS,不是受限节点或者访问过的节点才入队,每次入队的时候计数
class Solution {
public:
int reachableNodes(int n, vector<vector<int>>& edges, vector<int>& restricted) {
unordered_map<int, vector<int>> g;
for(auto edge: edges) {
int a = edge[0], b = edge[1];
g[a].push_back(b);
g[b].push_back(a);
}
vector<bool> st(n, false);
unordered_set<int> us = {restricted.begin(), restricted.end()};
queue<int> q;
q.push(0);
st[0] = true;
int cnt = 1;
while(!q.empty()) {
int ver = q.front();
q.pop();
for(int j: g[ver]) {
if(!st[j] && us.find(j) == us.end()) {
q.push(j);
st[j] = true;
cnt++;
}
}
}
return cnt;
}
};
bfs还得找时间好好学学😓
AcWing第63场周赛
数对数量
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int a,b,n;
cin >> a;
cin >> b;
cin >> n;
int k=0;
for (int i = 0; i <=a; i ++ )
{
for (int j = 0; j <=b; j ++ )
{
if(i+j==n)k++;
}
}
cout << k;
}
这是O(n²)做法,在题解哪看到了O(1)解法
#include <bits/stdc++.h>
using namespace std;
int a, b, n;
int main() {
cin >> a >> b >> n;
cout << n + 1 - max(n - a, 0) - max(n - b, 0);
}
解释:首先,题目说了,和为nn的数对就只有(0,n),(1,n−1),(2,n−2),⋯,(n−2,2),(n−1,1),(n,0) n+1对
但是,第一个数有大小限制的,我们就需要知道由于第一个数答案少了几对,少的就是第一个数从a+1开始到nn结束的那几对,少了n−a对,第二个数同理
但是有可能没少,所以我们把差和0取个max
👍👍👍👍
字符串消除
每次比较栈顶与当前字符匹配并且不为空的情况下字符栈顶出栈,并且答案+1,否则将字符入栈
#include <bits/stdc++.h>
using namespace std ;
const int N = 1e5 + 5 ;
string a ;
stack < char > stk ;
int main(){
int res = 0 ;
cin >> a ;
int n = a.size () ;
stk.push (a[0]) ;
for (int i = 1; i < n; i ++) {
if (! stk.empty () && a[i] == stk.top ()) {
stk.pop () ;
res ^= 1 ;
} else {
stk.push (a[i]) ;
}
}
cout << (res & 1 ? "Yes" : "No") ;
return 0;
}
这个又用到了栈的解法,我还需要花时间熟悉一下栈方面的算法