【发布时间】:2021-01-08 08:22:43
【问题描述】:
在解决this 问题时,我在条件检查中直接使用ArrayList 的get 方法在该问题的一些测试用例上得到错误答案。
测试用例失败的代码:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
Stack <Integer> s= new Stack<>();
ArrayList <Integer> m= new ArrayList<>();
for(int i=0;i<n;i++){
int x=sc.nextInt();
if(x==1){
int y=sc.nextInt();
if(m.isEmpty() || y>=m.get(m.size()-1))
m.add(y);
s.push(y);
}
else if(x==2){
// Here I am using `get` to check the last value of ArrayList with the top of stack
if(m.get(m.size()-1)==s.peek()) {
m.remove(m.size()-1);
}
s.pop();
}
else {
System.out.println(m.get(m.size()-1));
}
}
}
}
但是当将相同的语法分配给一个变量并将其用于它通过的条件检查时。
通过所有测试用例的代码:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
Stack <Integer> s= new Stack<>();
ArrayList <Integer> m= new ArrayList<>();
for(int i=0;i<n;i++){
int x=sc.nextInt();
if(x==1){
int y=sc.nextInt();
if(m.isEmpty() || y>=m.get(m.size()-1))
m.add(y);
s.push(y);
}
else if(x==2){
// When assigning the same to a variable it passed all test cases.
int a = m.get(m.size()-1);
if(a==s.peek()) {
m.remove(m.size()-1);
}
s.pop();
}
else {
System.out.println(m.get(m.size()-1));
}
}
}
}
由于我是 Java 新手,我对 ArrayList 的 get 方法的使用感到困惑。请向我解释 get 方法的内部工作原理,为什么它会失败或我遗漏了什么?
【问题讨论】:
-
你查看过ArrayList的文档吗? docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/…
-
@Stultuske yaa 我已经检查过了...但仍然不清楚之前代码的问题在哪里...
-
您不清楚问题所在。您能否详细说明并发布一个最小的复制示例?