【发布时间】:2021-06-02 09:30:57
【问题描述】:
我有一个包含成对整数示例的列表 -> [{1,2},{2,3},{2,1}]
我想从中删除重复的元素,就像 (1,2) 和 (2,1) 一样。
这是我的代码 ->
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
在这里,我首先将 2 个整数转换为单个字符串,然后将其插入哈希集中。 有人可以告诉我上述代码的性能和时间复杂度吗?
【问题讨论】:
-
t1 和 t2 什么都不做。你的对总是存储整数。因此,您可以删除这些类型参数,并且相当多的声明会更短
-
@Michael 但是性能和时间复杂度是多少?
标签: java