有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java在数组中查找重复的元素并将其显示为子数组

我需要找到所有重复的数组元素,并将它们显示为单独的子数组。大概是这样的:

数组={1,7,4,3,5,5,2,1,1,8,9,8,0,1,1,2}

  1. 数组0={0}
  2. 数组1={1,1,1,1,1}
  3. Array2={2,2}
  4. 数组3={3}
  5. 数组4={4}

。。。等等

我所做的:

  • 生成数组
  • 按升序排序

我试图弄明白,如何通过排序数组进行循环,并将其拆分为包含重复元素的独立子数组


共 (3) 个答案

  1. # 1 楼答案

    如果知道值的范围,可以创建另一个数组并将值添加到相应的数字中。然而,正如前面提到的,使用HashMap会容易得多

  2. # 2 楼答案

    仅使用数组和数组列表

    我创建了另一个数组arr2[]作为该数组的副本,并开始比较所有值。 结果将被添加到一个临时Arraylist,该列表将被添加到主输出集合Arraylist<ArrayList<Integer>

    import java.util.ArrayList;
    import java.util.Arrays;
    
    public class temp
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            int arr[]=  {1,7,4,3,5,5,2,1,1,8,9,8,0,1,1,2};
            int arr2[]= Arrays.copyOf(arr,arr.length);
    
    
            ArrayList<ArrayList<Integer>> arrList= new ArrayList<ArrayList<Integer>>();  
    
            System.out.println(Arrays.toString(arr));
    
            for (int i = 0; i < arr.length; i++) {
            ArrayList<Integer> tempArr = new ArrayList<Integer>();
            int count=0;
            for (int j = 0; j < arr2.length; j++) {
    
                if(arr[i]==arr2[j] &&arr2[j]!=-1)
                {   tempArr.add(arr[i]);
                    arr2[j]=-1;
                }
            }
            if(tempArr.size()>1) arrList.add(tempArr);
        }
    
        for(ArrayList c: arrList)
        {           
            System.out.println(c);
        }
    
    }
    
    
    
    
    }  
    

    输出:

    [1, 7, 4, 3, 5, 5, 2, 1, 1, 8, 9, 8, 0, 1, 1, 2]
    [1, 1, 1, 1, 1]
    [5, 5]
    [2, 2]
    [8, 8]
    
  3. # 3 楼答案

    您可以使用下面的通用方法来分离重复项:

    public static <T> HashMap<T, List<T>> getDuplicates(T[] array){
        HashMap<T, List<T>> result = new HashMap<T, List<T>>();
        for(T item : array){
            List<T> duplicates = result.get(item);
            if(duplicates == null)
                result.put(item, duplicates = new ArrayList<T>());
            duplicates.add(item);
        }
        return result;
    }
    

    接下来,您可以按方法对结果集合进行排序:

    public static <T extends Comparable<T>> List<List<T>> getSorted(HashMap<T, List<T>> groups){
        List<List<T>> sortedGroups = new ArrayList<>(groups.values());
        Collections.sort(sortedGroups, new Comparator<List<T>>() {
            @Override
            public int compare(List<T> g1, List<T> g2) {
                if(g1.isEmpty())
                    return -1;
                else if(g2.isEmpty())
                    return 1;
                else 
                    return g1.get(0).compareTo(g2.get(0)); 
            }
        });
        return sortedGroups;
    }