获取数组中所有重复的元素

  • 给定一个数组,判断该数组中是否含有。若有,输出该数组中所有重复的元素,返回true;若无,返回false。
  • 示例,如下数组numbers,输出[2,3,5],返回true
    int[] numbers = {1,3,4,5,5,3,2,3,2,2,2};

1.思路

  现将数组numbers按照从小到大进行排序(从大到小亦可),然后依次比较相邻的两个元素,若两元素相同,则为重复元素,将其存入数组duplication中。

  需要注意的是,如果存在多个(大于3个)相同的相邻元素时,duplication数组也会出现重复的元素,如有四个相同的相邻元素2{2,2,2,2},按照前面的做法,duplication数组中会有三个2(因为连续三次比较结果都相同),不满足题目需求。

  解决此bug的方法有两个(目前博主只能想到这两个):

1)根据连续比较次数,判断是否应该将当前重复元素存入duplication数组。思路如下:

int 比较次数 = 0;

for(.......遍历排序后的数组numbers.....){

  if(当前数组元素 == 下一个数组元素)

    temp++;

    if(如果比较次数 == 1)

      当前重复元素存入duplication数组;

  else

    比较次数 = 0;

}

2)利用集合Set的特性——元素唯一性。简单介绍思路如下

  定义一个集合对象set,遍历遍历排序后的数组numbers时,在set中添加 满足if(当前数组元素 == 下一个数组元素 && set中不包含当前数组元素)的元素,

2.供参考代码

 1 import java.util.*;
 2 
 3 public class TEST{
 4     public static void main(String[] args) {
 5         TEST t = new TEST();
 6         int[] numbers = {1,3,4,5,5,3,2,3,2,2,2};
 7         int[] dup = new int[numbers.length/2+1];
 8 
 9         System.out.println("原numbers数组:");
10         for (int i = 0; i < numbers.length; i++) {
11             System.out.println("numbers["+i+"]:"+numbers[i]);
12         }
13 
14         if(t.duplicate(numbers,numbers.length,dup))
15         {
16             System.out.println("含有重复元素dup:");
17             for (int i = 0; i < dup.length; i++) {
18                 System.out.println("dup["+i+"]:"+dup[i]);
19             }
20         }
21 
22     }
23     public boolean duplicate(int[] numbers,int length,int[] duplication) {
24         if (numbers == null || length==0)
25             return false;
26 
27         Arrays.sort(numbers);
28 
29         int temp=0,j = 0,duplen=0;
30         for(int i=0;i<length-1;i++){
31             if (numbers[i] == numbers[i+1]){
32                 temp++;
33                 /*
34                 * 当且仅当两个相邻的值相同一次(temp == 1)便积累重复数组duplication中去,
35                 * 如接连有三个以上的相邻值相同如四个2{2,2,2,2}共有三次比较,
36                 * 第一次{2,2}比较时候,temp++==1,可存入duplication数组,{2,2,2}后两次比较temp++==2,temp++==3
37                 * temp的值均不满足条件if (temp == 1),故duplication不会之前已存的数据
38                 * */
39                 if (temp == 1){
40                     duplication[j++] = numbers[i];
41                     duplen++;
42                 }
43             }else{
44                 temp = 0;            }
45         }
46         if(duplen == 0){
47             return false;
48         }else {
49             return true;
50         }
51     }
52 }

猜你喜欢

转载自www.cnblogs.com/EricGao/p/11735923.html