1. 用栈操作构建数组
class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
stack<int> st;
vector<string> ans;
int now = 1;
int ind = 0;
int N = target.size();
while(ind<N)
{
if(now==target[ind])
{
ans.push_back("Push");
ind++;
}
else{
ans.push_back("Push");
ans.push_back("Pop");
}
now = now%n+1;
}
return ans;
}
};
2. 形成两个异或相等数组的三元组数目
class Solution {
public:
int countTriplets(vector<int>& arr) {
int N = arr.size();
int ans = 0;
for(int i=0;i<N-1;i++)
{
int left = 0;
for(int j=i+1;j<N;j++)
{
left = left^arr[j-1];
int right = 0;
for(int k=j;k<N;k++)
{
right = right^arr[k];
if(left==right)
{
ans++;
}
}
}
}
return ans;
}
};
3. 收集树上所有苹果的最少时间
思路
遍历有苹果的节点,然后不断访问父节点,直到该节点已经被访问过或者该节点是根节点。比赛的时候想到了这种方法,但是没调出来。。。。是真菜。。。
解法1
class Solution {
public:
int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {
int N = hasApple.size();
vector<int> father;
vector<bool> visited;
father.resize(N);
visited.resize(N);
father[0] = -1;
for(auto edge:edges)
{
father[edge[1]] = edge[0];
}
int ans = 0;
for(int i=1;i<N;i++)
{
if(hasApple[i]&&!visited[i])
{
int tmp = i;
visited[tmp] = true;
ans++;
while(father[tmp]!=0&&!visited[father[tmp]])
{
tmp = father[tmp];
visited[tmp] = true;
ans++;
}
}
}
return ans*2;
}
};
解法2
还可以用dfs,先占位,理解之后再更。