【发布时间】:2021-08-08 13:27:12
【问题描述】:
我有一个 ArrayList,其中包含整数对(比如 int i、int j)。但它可能包含重复对(如(int i, int j) 和(int j, int i))。现在如何以 O(n) 的时间复杂度从中删除重复项。
更新代码:
class Pair<t1,t2>
{
int i, j;
Pair(int i,int j){
this.i=i;
this.j=j;
}
}
public class My
{
public static void main(String[] args) {
Pair p;
List<Pair<Integer,Integer>> src = Arrays.asList(new Pair(1,2),
new Pair(2,3), new Pair(2,1),new Pair(1,2));
HashSet<String> dest = new HashSet();
for(int i=0; i < src.size(); i++) {
p=src.get(i);
if(dest.contains(p.j+" "+p.i)) {
System.out.println("duplicacy");
}
else {
dest.add(p.i+" "+p.j);
}
}
System.out.println("set is = "+dest);
List<Pair<Integer,Integer>> ans=new ArrayList();
String temp;
int i,j;
Iterator<String> it=dest.iterator();
while(it.hasNext())
{
temp=it.next();
i=Integer.parseInt(temp.substring(0,temp.indexOf(' ')));
j=Integer.parseInt(temp.substring(temp.indexOf('
')+1,temp.length()));
ans.add(new Pair(i,j));
}
for(Pair i_p:ans) {
System.out.println("Pair = "+i_p.i+" , "+i_p.j);
}
}//end of main method
}//end of class My
这段代码运行良好,但我想知道它的性能,我的意思是它的整体时间复杂度?
【问题讨论】:
-
你说的是
javafx.util.Pair吗?你能展示你的代码和你尝试过的东西吗?(1, 2)是(2, 1)的副本吗?您还应该显示您的输入和预期输出。
标签: java performance arraylist