方法一(采用HashSet)
public static Set<Integer> getSameElement(Integer[] a, Integer[] b) {
Long start = System.currentTimeMillis();
Set<Integer> temp = new HashSet<Integer>();
Set<Integer> same = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
temp.add(a[i]);
}
for (int j = 0; j < b.length; j++) {
if (!temp.add(b[j])) {
same.add(b[j]);
}
}
System.out.println("HashSet用时:" + (System.currentTimeMillis() - start));
return same;
}
public static Set<Integer> getSameElement(Integer[] a, Integer[] b) {
Long start = System.currentTimeMillis();
Set<Integer> temp = new HashSet<Integer>();
Set<Integer> same = new HashSet<Integer>();
Integer[] max = a.length > b.length ? a : b;
Integer[] min = a.length > b.length ? b : a;
for (int i = 0; i < max.length; i++) {
temp.add(max[i]);
}
for (int j = 0; j < min.length; j++) {
if (!temp.add(min[j])) {
same.add(min[j]);
}
}
System.out.println("HashSet用时:" + (System.currentTimeMillis() - start));
return same;
}
方法二(采用list)
public static List<Integer> getSamelElement(Integer[] a,Integer[] b){
List<Integer> aList = Arrays.asList(a);
List<Integer> bList = Arrays.asList(b);
List<Integer> sameList = new ArrayList<Integer>();
for(Integer in : aList){
if(bList.contains(in)){
sameList.add(in);
}
}
return sameList;
}
public static List<Integer> getSameElement(Integer[] a, Integer[] b) {
Long start = System.currentTimeMillis();
List<Integer> aList = new ArrayList<Integer>();
List<Integer> bList = new ArrayList<Integer>();
List<Integer> resultList = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
aList.add(a[i]);
}
for (int j = 0; j < b.length; j++) {
bList.add(b[j]);
}
List<Integer> smallList = a.length > b.length ? bList : aList;
List<Integer> bigList = a.length > b.length ? aList : bList;
for (int k = 0; k < smallList.size(); k++) {
int temp = smallList.get(k);
if (bigList.contains(temp)) {
resultList.add(temp);
}
}
System.out.println("List用时:" + (System.currentTimeMillis() - start));
return resultList;
}
推荐采用方法一
Remark:QQ交流群:260052172