题目:已知有一个无序的数组中存在重复的元素,要求去掉重复元素后输出新数组。
分析:
set中的元素是不能重复的。所以我们可以先判断set中有没有该元素,如果没有就进行添加到set中,直到遍历完所有数组元素,最后set输出为数组,使用set的toArray方法,可以将set转为数组存储。
代码片段:
public static Object[] remove(int[] nums){
Set<Integer> set=new HashSet<>();
for(int i=0;i<nums.length;i++){
if(!set.contains(nums[i])){
set.add(nums[i]);
}
}
//返回数组格式
return set.toArray();
}