LeetCode周赛记录20200223
文章目录
从今天开始只记录周赛题,单双周赛合并记录。
5172 形成3的最大倍数(hard)
class Solution {
public:
string largestMultipleOfThree(vector<int>& digits) {
int ps[10];
memset(ps, 0, sizeof(ps));
int sum = 0;
for(auto d: digits)
{
++ps[d];
sum += d;
}
if(sum%3==2)
{
if(!del(2, ps))
{
del(1, ps);
del(1, ps);
}
}
else if(sum%3==1)
{
if(!del(1, ps))
{
del(2, ps);
del(2, ps);
}
}
else;
string res;
for(int i=9;i>0;--i)
res += string(ps[i], i+'0');
if(res.empty())
{
if(ps[0] != 0)
res += string(1, '0');
return res;
}
res += string(ps[0], '0');
return res;
}
int del(int s, int ps[])
{
for(int i=s;i<10;i+=3)
{
if(ps[i]>0)
{
--ps[i];
return 1;
}
}
return 0;
}
};
5170 验证二叉树(mid)
class Solution {
public:
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
vector<int> flags(n, -1);
for(int i=0;i<n;++i)
{
stack<int> st;
st.push(i);
while(!st.empty())
{
while(leftChild[st.top()] != -1)
{
int left = leftChild[st.top()];
if(flags[left] != -1 && flags[left] != st.top())
return false;
else if(flags[left] != -1)
break;
else
flags[left] = st.top();
st.push(left);
}
while(!st.empty())
{
auto t = st.top();
st.pop();
int right = rightChild[t];
if(right == -1)
continue;
if(flags[right] != -1 && flags[right] != t)
return false;
else if(flags[right] == -1)
{
flags[right] = t;
st.push(right);
break;
}
else;
}
}
}
int cnt = 0;
for(int i=0;i<n;++i)
{
if(flags[i] == -1)
++cnt;
}
return cnt == 1;
}
};
5325 包含所有三种字符的子字符串数目(mid)
写了个题解:https://leetcode-cn.com/problems/number-of-substrings-containing-all-three-characters/solution/fu-zhu-dui-lie-bian-li-yi-bian-by-wiennan/
class Solution {
public:
using His = array<int, 3>;
int numberOfSubstrings(string s) {
queue<His> q;
His g{0,0,0};
q.push(g);
int res = 0;
for(int i=0;i<s.size();++i)
{
++g[s[i]-'a'];
while(!q.empty() && check(q.front(), g))
{
q.pop();
res += (s.size() - i);
}
q.push(g);
}
return res;
}
bool check(const His& i1, const His& i2)
{
return i1[0]<i2[0]&&i1[1]<i2[1]&&i1[2]<i2[2];
}
};
5326 有效的快递序列数目(hard)
初高中数学题
class Solution {
public:
int countOrders(int n) {
long long res = 1;
for(int i=2*n;i>2;i-=2)
{
res *= ((i * (i-1))/2);
res %= 1000000007;
}
return res;
}
};