两棵树
两棵树的问题
http://www.nowcoder.com/questionTerminal/ae592e8b25f041b28dbc27b986441085
这题我超时了,思路应该 是对滴,本地用例通过了。
class Solution {
public:
/**
*
* @param n int整型
* @param a int整型一维数组
* @param aLen int a数组长度
* @param b int整型一维数组
* @param bLen int b数组长度
* @param c int整型一维数组
* @param cLen int c数组长度
* @return int整型
*/
//在树中找到每个节点的路径,对路径进行比较
int findLength(int first, int second, int* a, int aLen) {
int tmp = first;
if (first == 0)
return 0;
//存储节点1的路径
std::vector<int> dp;
while (first != 0) {
if (a[first] != 0 && a[first] != second)
{
first = a[first];
dp.push_back(first);
}
else {
if (a[first] == second)
return 0;
else
if (a[first] == 0)
break;
}
}
dp.push_back(0);
//存储节点2的路径
std::vector<int> dp1;
while (second != 0) {
if (a[second] != 0 && a[second] != tmp) {
second = a[second];
dp1.push_back(second);
}
else {
if (a[second] == tmp)
return 0;
else
if (a[second] == 0)
break;
}
}
dp1.push_back(0);
//计算公共节点的深度
int result = -1;
int start = dp.size() - 1;
int start1 = dp1.size() - 1;
while (start >= 0 && start1 >= 0&&dp[start] == dp1[start1]) {
result += 1;
start -= 1;
start1 -= 1;
}
return result;
}
int wwork(int n, int* a, int aLen, int* b, int bLen, int* c, int cLen) {
// write code here
//a数组是用来对b数组编号进行映射,可以在c中找到对应的编号。
// b中为2 3编号的节点,对应a的编号为a[2]=1,a[3]=3,也就是说在c中找到这两个编号即
//c[1],c[3]
//超时了,你们可以优化下,我本地通过。
int result = 0;
for(int i=1;i<n;++i){
for(int j=i+1;j<=n;++j){
int tmp = findLength(i,j,b,bLen);
int first = a[i];
int second = a[j];
tmp += findLength(first,second,c,cLen);
if(tmp>result)
result = tmp;
}
}
return result;
}
};
vivo公司福利 363人发布
查看14道真题和解析