Java 两个堆栈的黑客游戏
我看不出下面的代码有什么问题,我的解决方案无法通过Hackerrank上的测试用例,你能给我举个例子说明我的代码失败的地方吗?非常感谢您的帮助,谢谢 以下是问题陈述: 以下是我提出的解决方案:Java 两个堆栈的黑客游戏,java,stack,Java,Stack,我看不出下面的代码有什么问题,我的解决方案无法通过Hackerrank上的测试用例,你能给我举个例子说明我的代码失败的地方吗?非常感谢您的帮助,谢谢 以下是问题陈述: 以下是我提出的解决方案: static int twoStacks(int x, int[] a, int[] b) { Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new
static int twoStacks(int x, int[] a, int[] b) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
for(int i=a.length-1;i>=0;i--) {
stack1.push(a[i]);
}
for(int i=b.length-1;i>=0;i--) {
stack2.push(b[i]);
}
int counter = 0;
int sum = 0;
int top1, top2;
while(sum<=x) {
top1 = stack1.peek();
top2 = stack2.peek();
if(top1<=top2) {
sum+=top1;
stack1.pop();
} else if (top2< top1) {
sum+=top2;
stack2.pop();
}
if(sum<=x) {
counter++;
}
}
return counter;
}
静态int-twostack(int x,int[]a,int[]b){
Stack stack1=新堆栈();
Stack stack2=新堆栈();
对于(int i=a.length-1;i>=0;i--){
stack1.推(a[i]);
}
对于(int i=b.length-1;i>=0;i--){
stack2.push(b[i]);
}
int计数器=0;
整数和=0;
int top1、top2;
while(sum您的解决方案是错误的,因为如果sum
从未大于或等于x
,则您的while
循环不会终止。您的计数器将永远增加
当两个堆栈都为空时,您需要添加一个中断
if(stack1.empty() && stack2.empty())
break;
谢谢你的回答,你是对的;不幸的是,这无助于通过hackerrank的13个测试用例,我仍然只通过了13个测试用例中的2个。@BrunoMo Yep,这是另一个。假设两个堆栈中只有一个变为空。当你偷看一个空堆栈时,它会抛出一个EmptyStackException
。你需要停止偷看当其中一个堆栈变空时,从两个堆栈中选择并比较它们的值。只需继续从另一个堆栈中弹出。解释您的期望和得到的结果(至少)。始终在两个堆栈中选择最小的元素不会为您提供最优化的解决方案,例如x=6,stack1=[3,3,3],stack2=[4,1,1]。正确答案将选择stack2的3个元素,而您的算法将选择stack1的前2个元素。