我尝试在技术面试的在线评估中解决以下问题,但失败了。我已经思考这个问题有一段时间了,似乎找不到令我满意的答案:
您正在寻找数组 A 的最长前导片段(前缀),其中 X 和 Y 出现的次数相等,其中 X 和 Y 是整数。
例如,当 X=7 且 Y=42 时,A=[6, 42, 11, 7, 1, 42] 的最长前缀将为 4,因为 A[0]-A[4] 包含相同数量的X 和 Y。
另一个例子,X=6,Y=13。A=[13,13,1,6]。该函数应返回 -1,因为没有前缀。
X=100、Y=63 和 A=[100,63,1,6,2,13] 应返回 5。
我尝试用 C 语言回答:
int solution(int X, int Y, int A[], int N){
int result=-1;
int nX=0; //number of occurrences of X
int nY=0; //number of occurrences of Y
int i;
for(i=0;i<N;i++){//loop through the input array
if(A[i]==X)//occurrence of X
nX += 1;
/*
EDGE CASE BELOW: this should have been an if
statement, because X and Y could be the same
number. I know I missed this in the assessment,
but believe there is another issue, because I
failed almost all the test cases generated by the
assessment.
*/
else if(A[i]==Y)//occurrence of Y
nY += 1;
if((nX!=0)&& (nX==nY))//same number of X and Y
//and there is at least one occurence of each
result=i;//longest prefix is the index
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我无法自己生成失败的测试用例,并且失败的测试用例隐藏在评估中。因此我无法提供太多有帮助的信息。
我确实知道,每次失败时,我的程序都会返回 -1 而不是正确答案。
如果你们中的任何一个人通过思考就能发现一些问题,我很乐意看看我错过了什么。谢谢!
如果您准确地描述了要求,那么它们不会指定X和Y出现的相同正数。零有效。
所以这:
if((nX!=0)&& (nX==nY))//same number of X and Y
//and there is at least one occurence of each
result=i;//longest prefix is the index
}
Run Code Online (Sandbox Code Playgroud)
应该是这样的:
if(nX==nY)//same number of X and Y
result=i;//longest prefix is the index
}
Run Code Online (Sandbox Code Playgroud)
没有检查nX!=0. 因此,如果X未出现在数组中和/或Y未出现在数组中,则代码不必要地返回 -1。
此外,这些要求似乎并不能保证X和Y不同;如果不是,那么您的代码将返回 -1,但根据需求的字面解读,答案将是N -1。