首页 > 解决方案 > 对数组进行排序并找到重复的数字

问题描述

package array;

import java.util.Arrays;

public class learning_program1 {

    public static void main(String[] args) {

        int arr[]= {1,2,3,4,10,20,30,6,6,5,4,5,5,2};

        Arrays.sort(arr);
        for(int i = 0; i < arr.length; i++) 
        {   
            int count =0;
            int flag=0;
            for(int j=i+1; j<arr.length; j++)
            {
                while(arr[i] == arr[j])
                {
                    count++;
                    j++;
                    flag=1;
                }
                break;
            }
            if(flag==1)
            {
                System.out.println("the repeated values " + arr[i] + " is " +count);
            }


        }

    }
}

输出:

重复值 2 为 1

重复值 4 为 1

重复值 5 为 2

重复值 5 为 1

重复值 6 为 1

我的问题是我得到了输出,但是 5 重复了两次

标签: javaarrays

解决方案


您可以使用Stream. 首先,您必须按其值对给定中的所有元素进行分组arr并计算它们。然后,过滤出现多次的元素。

public static Map<Integer, Integer> findDuplicates(int[] arr) {
    Map<Integer, Long> map = Arrays.stream(arr)
                                   .boxed()
                                   .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    Map<Integer, Integer> res = new TreeMap<>();

    map.entrySet().stream()
       .filter(entry -> entry.getValue() > 1)
       .forEach(entry -> res.put(entry.getKey(), entry.getValue().intValue() - 1));

    return res;
}

在这种情况下,您的客户端代码将如下所示:

int arr[] = { 1, 2, 3, 4, 10, 20, 30, 6, 6, 5, 4, 5, 5, 2 };
Map<Integer, Integer> map = findDuplicates(arr);
map.forEach((key, count) -> System.out.println("the repeated values " + key + " is " + count));

输出:

the repeated values 2 is 1
the repeated values 4 is 1
the repeated values 5 is 2
the repeated values 6 is 1

PS 如果您犹豫使用Stream,没有它很容易做到,只需依靠Setand Map

public static Map<Integer, Integer> findDuplicates(int[] arr) {
    Set<Integer> values = new HashSet<>();
    Map<Integer, Integer> map = new TreeMap<>();

    for (int val : arr)
        if (!values.add(val))
            map.put(val, map.getOrDefault(val, 0) + 1);

    return map;
}

推荐阅读