数组去重

java-两种方法求两个数组中重复的元素

第一种方法:暴力法

 1 public static ArrayList<Integer> FindSameNum(int[] arr1,int[] arr2){
 2         ArrayList<Integer> list = new ArrayList<>();
 3         for(int i = 0; i<arr1.length;i++){
 4             for(int j = 0; j < arr2.length; j++){
 5                 if(arr1[i] == arr2[j]){
 6                     list.add(arr1[i]);
 7                 }
 8             }
 9         }
10         return list;
11     }

第二种:借助hashset数据结构

 1 public static Set<Integer> getSames(int[] m,int[] n){
 2         HashSet<Integer> common = new HashSet<>();  //保存相同的元素
 3         HashSet<Integer>  different = new HashSet<>(); //保存不同的元素
 4 
 5         for(int i = 0; i<m.length;i++){
 6             different.add(m[i]);
 7         }
 8 
 9         for(int j = 0; j < n.length;j++){
10             if(!different.add(n[j])){  
11                 different.add(n[j]);
12             }
13         }
14         return common ;
15     }
View Code

小结:

  第一种方法:使用两层for循环进行遍历

  缺点:时间复杂度太高(不建议使用)。

  第二种方法:利用hashset中的去重原理。

    思路:利用hashset集合中没有重复元素的特性。

    1、声明两个hashset对象common和different(分别保存两个数组中的相同元素和不同元素)

    2、先将a数组添加到different集合中

    3、将b数组的元素添加到different中

原文地址:https://www.cnblogs.com/xiaocao123/p/10613788.html