LeetCode 94场双周赛
Q1
傻逼题意,总而言之就是找出最近的两个1和-1之间的位置距离最大。
C++代码:
class Solution {
public:
int captureForts(vector<int>& forts) {
int n=forts.size(),ans=0,a=-1,b=-1;
for(int i=0;i<n;i++){
if(forts[i]==1){
a=i;
if(b!=-1) ans=max(abs(a-b)-1,ans),b=-1;
}else if(forts[i]==-1){
b=i;
if(a!=-1) ans=max(abs(a-b)-1,ans),a=-1;
}
}
return ans;
}
};
Q2
就是排序题,但是用python超时了,真是傻逼,还想着方便些。写的很啰嗦。待会儿学习一下别人的代码。
C++代码:
class Solution {
public:
vector<int> topStudents(vector<string>& pos, vector<string>& neg, vector<string>& report, vector<int>& id, int k) {
set<string> p,n;
for(auto&x:pos) p.insert(x);
for(auto&x:neg) n.insert(x);
vector<pair<int,int> > a;
for(int i=0;i<report.size();i++){
string s=report[i];
string tmp="";
vector<string> L;
for(int i=0;i<s.size();i++){
if(s[i]!=' ') tmp+=s[i];
else{
L.push_back(tmp);
tmp="";
}
}
if(tmp!="") L.push_back(tmp);
int score=0;
for(auto&x:L){
if(p.count(x)) score+=3;
if(n.count(x)) score-=1;
}
a.push_back({score,id[i]});
}
sort(a.begin(),a.end(),[&](pair<int,int> a,pair<int,int> b){
if(a.first==b.first) return a.second<b.second;
return a.first>b.first;
});
vector<int> ans;
for(auto&x:a){
ans.push_back(x.second);
--k;
if(!k) break;
}
return ans;
}
};
Q3
留个位置,暂时没想到咋做。
Q4
逆元,阶乘模板题。把以前板子拿过来,就可以了。
除法的取模等于乘以他的逆元。例如求x的逆元,就是 x m o d − 2 x^{mod-2} xmod−2 对 mod取模
C++代码:
const int mod = 1e9+7;
const int N=100007;
typedef long long ll;
ll fact[N],infact[N];
ll qmi(ll a, ll k, ll p)
{
ll res = 1;
while (k)
{
if (k & 1) res = (ll)res * a % p;
a = (ll)a * a % p;
k >>= 1;
}
return res;
}
void init(int n)
{
fact[0] = infact[0] = 1;
for (int i = 1; i <=n; i ++ )
{
fact[i] = (ll)fact[i - 1] * i % mod;
infact[i] = (ll)infact[i - 1] * qmi(i, mod - 2, mod) % mod;
}
}
class Solution {
public:
int countAnagrams(string s) {
init(100001);
string tmp="";
vector<string> L;
for(int i=0;i<s.size();i++){
if(s[i]!=' ') tmp+=s[i];
else{
L.push_back(tmp);
tmp="";
}
}
if(tmp!="") L.push_back(tmp);
ll ans=1;
for(auto&x:L){
map<char,int> dict;
for(auto&c:x) dict[c]+=1;
int l=x.size();
ans=ans*1ll*fact[l]%mod;
for(auto&[k,v]:dict){
ans=ans*infact[v]%mod;
}
}
return ans;
}
};
总结:本来写这三道题应该很快的,但是傻逼了,第一题读题读半天,一开始还理解错意思了,第二题用Python超时,结果改用C++重写一遍,第四题犹豫半天会不会爆ll。
大总结:真的菜,真的傻逼。