首页 > 解决方案 > 如何摆脱打印行中的重复项

问题描述

在过去的 5 个小时里,我一直在尝试解决这个问题,但我已经筋疲力尽了..
我需要构建一个方法,该方法需要一个数字数组并确定在 thr 数组中哪个正确的数字显示次数最少。例如,如果数组是 [134,12634,124,5667] 将显示的数字是 7 .. 我希望我足够清楚:(

无论如何,这是代码。我设法到达它显示数字的部分,但它会显示它的次数与循环运行的次数一样多。

请帮忙

public static boolean QuestionD(int[] arr)
    {
        int counter = 0;
        int printNum = 0;
        String[] arr2 = new String[arr.length];
        int[] arr3 = new int[arr.length];
        for (int i = 0; i < arr.length; i++)
            if (arr[i] < 0)
                return false;//if the numbers are negative return false;
        for (int j = 0; j < arr.length; j++)
        {
            printNum = arr[j] % 10;// get the right digit of the number
            {
                for (int i = 0; i < arr.length; i++)
                    if (arr[i] % 10 == printNum)// if the right digit of the first index matches the other index then counter ++;
                        counter++;// to count how many times the right digit is shown
                arr2[j] = printNum + "" + counter;// to make the number as a string and will be 2 digits , the first digit from the left
                //will be the digit that appears on the right , and the second digit will be the times that the digit appeared
                arr3[j] = Integer.parseInt(arr2[j]);//make it back to an int
                counter = 0;// setting counter back to zero to check the other numbers
            }
        }
        
        for (int i = 0; i < arr.length; i++)
        {
            for (int j = i + 1; j < arr.length; j++)
                if (arr3[i] % 10 < arr3[j] % 10)
                    System.out.print((arr3[i] / 10 % 10) + " ");// here i take the digits that were shown the less but will duplicates 
            //as many times as the for loop runs for.
        
        }
        
        return true;
    }

标签: java

解决方案


如果您有兴趣使用 Map 来存储频率而不是数组(在这种情况下,您不需要处理频率为零的数字)。您可能会发现此解决方案很有帮助。在这里,我只是填充频率图,然后获取具有最小值的条目:

private static int getLeastFrequentDigit(int[] array) {
    Map<Integer, Integer> digitFrequencyMap = new HashMap<>();

    for (int j : array) {
        int key = j % 10;
        digitFrequencyMap.merge(key, 1, Integer::sum);
    }

    Map.Entry<Integer, Integer> minEntry = digitFrequencyMap.entrySet().stream()
            .min(Comparator.comparingInt(Map.Entry::getValue))
            .orElse(null);
    return minEntry != null ? minEntry.getKey() : -1;
}

推荐阅读