数组去重

时间:2019-03-28
本文章向大家介绍数组去重,主要包括数组去重使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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