java删除数组中重复的元素实例。什么方法效率比较高。
private static int [ ] supRep( int [ ] x) {
int[] tempArray = new int[x.length];
boolean repeated = false;
int nbNonRep=0;
//通过for语句遍历验证重复的元素
for (int i=0; i<x.length; i++){
for (int j=i+1; j<x.length; j++){
if (x[i]==x[j]){// x[i] 为重复的元素
repeated = true;
break;
}
}
if (repeated == false){// 不重复的元素就加到数组里面
tempArray[nbNonRep++]=x[i];
}
repeated = false;
}
int[] resultArray = new int[nbNonRep];
System.arraycopy(tempArray, 0, resultArray, 0, nbNonRep);
return(resultArray);
}
public static void main(String[] args) {
int [ ] arr = new int[]{2,5,6,6,8,12,3,5};
int [] a = supRep(arr);
for (int i = 0; i<a.length; i++){
System.out.print(a[i]+ ” “);
}
}
————————————————————————-
运行结果:
run:
2 6 8 12 3 5 成功生成(总时间:0 秒)
————————————————————————-
以上是两个两个数比较的,家啊如数据量非常大,比如几万几十万或者更多数字,最好做一个Tree,这样浏览一遍你的Array就OK了
————————————————————————-
如果想要简单,用ArrayList就可以了:
ArrayList myList = new ArrayList();
for (int i=0; i<arr.length; i++){
if (!myList.contains(arr[i])) myList.add(arr[i]);
}
for (int i = 0; i<myList.size();i++){
System.out.print(myList.get(i) + “, “);
}
但是程序效率肯定是不高的
ArrayList:底层用数组实现的List 。
特点:查询效率高,增删效率低 轻量级 线程不安全。
HashSet:采用哈希算法来实现Set接口, 唯一性保证:重复对象equals方法返回为true ,重复对象hashCode方法返回相同的整数
不同对象 哈希码 尽量保证不同(提高效率)。
TreeMap:
集合是指一个对象可以容纳了多个对象(不是引用),这个集合对象主要用来管理维护一系列相似的对象。