力扣单周赛
一.算数三元组的数目
1.原题链接:力扣
2.解题思路:
三层for循环语句,若满足条件,则ans++,返回ans即可
3.参考代码:
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int ans = 0;
int n = nums.size();
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++)
for(int k = j + 1; k < n; k++){
if(nums[j] - nums[i] == diff && nums[k] - nums[j] == diff)ans++;
}
}
return ans;
}
};
二.受限条件下可到达节点的数目
1.原题链接:力扣
2.解题思路:
首先用哈希表neibor记录每个结点的邻居结点,之后用集合visited记录访问过的结点,一开始就可以把受限的结点全部放入visited中,之后把第0个结点压入队列进行正常的广度优先搜索,每次都将该结点的未被访问的邻居压入队列,统计个数即可。
3.参考代码:
class Solution {
public:
unordered_map<int, vector<int>> neibor;
unordered_set<int> visited;
int reachableNodes(int n, vector<vector<int>>& edges, vector<int>& restricted) {
for(vector<int> vec : edges){
neibor[vec[0]].push_back(vec[1]);
neibor[vec[1]].push_back(vec[0]);
}
for(int restri : restricted){
visited.insert(restri);
}
queue<int> bfs;
bfs.push(0);
int res = 0;
while(!bfs.empty()){
int nowVisit = bfs.front();
visited.insert(nowVisit);
bfs.pop();
res ++;
for(int next : neibor[nowVisit]){
if(!visited.count(next)){
bfs.push(next);
}
}
}
return res;
}
};
力扣双周赛
一.合并相似的物品
1.原题链接:力扣
2.解题思路:
维护一个map<int, int>mp,mp[i] 表示价值为 i 的物品的重量之和,由于map是有序的,直接把遍历map的结果作为答案即可
3.参考代码:
class Solution {
public:
vector<vector<int>> mergeSimilarItems(vector<vector<int>>& items1, vector<vector<int>>& items2) {
map<int, int> mp;
for (auto &vec : items1) mp[vec[0]] += vec[1];
for (auto &vec : items2) mp[vec[0]] += vec[1];
vector<vector<int>> ans;
for (auto it = mp.begin(); it != mp.end(); it++){
ans.push_back(vector<int>{it->first, it->second});
}
return ans;
}
};
二.统计坏数对的数目
1.原题链接:力扣
2.解题思路:
坏数对的数目,就是所有数对的数目,减去满足 i < j 且 j - i == nums[j] - nums[i] 的数对数目,把等式两边移项,变为nums[i] - i == nums[j] - j ,因此我们只需要维护一个umordered_map<int , int>mp,mp[x] 表示目前为止满足nums[i] - i == x 的 i 有几个,我们枚举 j ,并从答案中减去mp[nums[j] - j]的值即可
3.参考代码:
class Solution {
public:
long long countBadPairs(vector<int>& nums) {
int n = nums.size();
long long ans = 1LL * n * (n - 1) / 2;
unordered_map<int, int> mp;
for (int i = 0; i < n; i++) {
int t = nums[i] - i;
ans -= mp[t];
mp[t]++;
}
return ans;
}
};
AcWing
一.数对数量
1.原题链接:4503. 数对数量 - AcWing题库
2.解题思路:
两层for循环语句,若满足条件,则ans++,输出ans即可
3.参考代码:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int a, b, n;
cin >> a >> b >> n;;
int ans = 0;
for(int i = 0; i <= a; i++){
for(int j = 0; j <= b; j++){
if(i + j == n)ans++;
}
}
cout << ans;
return 0;
}
二.字符串消除
1.原题链接:4504. 字符串消除 - AcWing题库
2.解题思路:
先依次遍历s的每个字符,st相当于一个栈,如果遍历后的字符与栈顶的字符不同,则插入,如果相同,则弹出栈顶。用res用来记录相同时删除操作的次数,如果是奇数,则先手胜,否则,则先手败
3.参考代码:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
int main()
{
string s,st;
cin >> s;
int res = 0;
for (auto t:s)
{
if (st.back() == t)
{
st.pop_back();
res ++;
continue;
}
st += t;
}
if (res % 2) puts("Yes");
else puts("No");
return 0;
}