力扣第318场周赛
https://leetcode.cn/contest/weekly-contest-318/
1.对数组执行操作
首先执行题目要求操作,再实现将0与数组末尾的数交换功能
class Solution {
public:
void change0(vector<int>& nums){
int j=0;
for(int i=0;i<nums.size();i++){
if(nums[i]!=0)
nums[j++]=nums[i];
}
while(j<nums.size())nums[j++]=0;
}
vector<int> applyOperations(vector<int>& nums) {
int n=nums.size();
for(int i=0;i<n-1;i++)
{
if(nums[i]==nums[i+1]){
nums[i]*=2;
nums[i+1]=0;
}
}
change0(nums);
return nums;
}
};
使用长度为 K 滑动窗口来遍历数组,用map维护滑动窗口中的元素个数,当map.size=k时,更新最大值
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
unordered_map<int, int> mp;
long long sum = 0;
for (int i = 0; i < k; i++) {
mp[nums[i]]++;
sum += nums[i];
}
long long ans = 0;
if (mp.size() == k) {
ans = sum;
}
for (int i = k; i < nums.size(); i++) {
mp[nums[i - k]]--;
mp[nums[i]]++;
sum += nums[i] - nums[i - k];
if (mp[nums[i - k]] == 0) {
mp.erase(nums[i - k]);
}
if (mp.size() == k) {
ans = max(ans, sum);
}
}
return ans;
}
};
Acwing第76场周赛
反转后比较
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<bitset>
using namespace std;
const int N = 100;
string a,ch;
int main()
{
cin >> a >> ch;
int n = a.size()-1;
reverse(a.begin(), a.end());
if (a == ch) puts("YES");
else puts("NO");
return 0;
}
哈希表存储每个字符出现的次数,当字符出现次数为1时,数对为1,当字符出现次数大于1时,数对为次数的平方
#include <iostream>
#include <cstring>
#include <unordered_map>
#include <algorithm>
using namespace std;
typedef long long LL;
int main()
{
LL res;
string s;
unordered_map<char,long long> ma;
cin >> s;
for(int i = 0;i < s.size();i ++) ma[s[i]] ++;
for(auto x : ma)
{
if(x.second == 1) res += 1;
else res += x.second * x.second;
}
cout << res;
return 0;
}