题目:
package package1;
import java.util.*;
public class Remove {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> rlist = new ArrayList<>();
System.out.println("Input the number of elements:");
int n = input.nextInt();
System.out.println("Enter n integers:");
for (int i = 0; i < n; i++) {
Integer value = input.nextInt();
rlist.add(value);
}
removeDuplicate1(rlist);
System.out.print("The distinct integers are:");
for (Integer o : rlist) {
System.out.print(o + " ");
}
input.close();
}
// 两层循环方法
public static void removeDuplicate1(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(j).equals(list.get(i))) {
list.remove(j);
}
}
}
}
// 使用ArrayList类的contains()方法
public static void removeDuplicate2(ArrayList<Integer> list) {
ArrayList<Integer> temp = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
int element = list.get(i);
if (!temp.contains(element))
temp.add(element);
}
list.clear();
list.addAll(temp);
}
// 使用二分查找的方法
public static void removeDuplicate3(ArrayList<Integer> list) {
ArrayList<Integer> temp = new ArrayList<>();
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
int key = (int) it.next();
boolean flag = binarySearch(temp, key);
if (flag)
it.remove();
}
}
public static boolean binarySearch(ArrayList<Integer> list, int key) {
boolean flag = false;
int low = 0;
int high = list.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
int midEle = list.get(mid);
if (key < midEle)
high = mid - 1;
else if (key == midEle)
return true;
else
low = mid + 1;
}
list.add(low, key);
return flag;
}
// 使用HashSet
public static void removeDuplicate4(ArrayList<Integer> list) {
HashSet<Integer> temp = new HashSet<>();
for (int i = 0; i < list.size(); i++) {
int element = list.get(i);
if (!temp.contains(element))
temp.add(element);
}
list.clear();
list.addAll(temp);
}
}
运行结果: