001
[NOIP2010]数字统计_牛客题霸_牛客网 (nowcoder.com)
题目:
题解:
遍历L到R之间的每个数i,将i转化为字符串s,遍历s的每个字符,出现一次'2',次数增加一次。
#include <iostream>
using namespace std;
int main()
{
int L=0,R=0,ret=0;
scanf("%d %d",&L,&R);
for(int i=L;i<=R;i++)
{
string str=to_string(i);
int n=str.size();
for(int j=0;j<n;j++)
{
if(str[j]=='2')
{
ret++;
}
}
}
printf("%d",ret);
return 0;
}
002
两个数组的交集_牛客题霸_牛客网 (nowcoder.com)
题目:
题解:
创建两个哈希表hash1和hash2,分别存储nums1和nums2的元素,遍历hash1中值大于0的键,当在hash2中该键的值同样大于0时,则为公共元素。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
unordered_map<int, int> hash1;
unordered_map<int, int> hash2;
vector<int> res;
for(auto ch:nums1)
{
hash1[ch]++;
}
for(auto ch:nums2)
{
hash2[ch]++;
}
for(auto [a,b]:hash1)
{
if(b!=0)
{
if(hash2.count(a)>0)
{
res.push_back(a);
}
}
}
return res;
}
};
003
题解:
创建一个字符串st来模拟栈,遍历原字符串s,同时将字符逐个插入st中,当st.back()和遍历到的原字符串相同时,st.pop_back()掉这个字符,s继续向后遍历。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s,st;
cin>>s;
for(auto ch:s)
{
if(st.size() && st.back()==ch) st.pop_back();
else st.push_back(ch);
}
cout<<(st.size()==0?"0":st)<<endl;
}