java如何删除数组中重复的数字
可以使用HashSet来帮助删除数组中的重复数字。具体步骤如下:
创建一个HashSet集合,用于存储数组中的元素。
遍历数组,将每个元素添加到HashSet中。
创建一个新的数组,其大小为HashSet的大小。
再次遍历数组,将元素添加到新数组中,同时检查元素是否已经存在于HashSet中,如果存在则跳过。
返回新数组。
以下是一个示例代码:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 3, 2, 5};
int[] newArr = removeDuplicates(arr);
for (int num : newArr) {
System.out.print(num + " ");
}
}
public static int[] removeDuplicates(int[] arr) {
HashSet<Integer> set = new HashSet<>();
for (int num : arr) {
set.add(num);
}
int[] newArr = new int[set.size()];
int index = 0;
for (int num : arr) {
if (set.contains(num)) {
newArr[index++] = num;
set.remove(num);
}
}
return newArr;
}
}
在这个示例中,原始数组中包含重复的数字,经过removeDuplicates方法处理后,新数组中将不包含重复的数字。
阅读剩余
THE END