java - 如何摆脱打印行中的重复项
问题描述
在过去的 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;
}
解决方案
如果您有兴趣使用 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;
}
推荐阅读
- python - 检查 python argparse 中使用了哪个组
- c++ - 如何从文件中读取矩阵?(c++)
- python - 管道后 awk 中的文件名
- sql-server - 用分隔符打印从 1 到 1000 的素数
- r - uiOutput 和 renderUI 不起作用(R Shiny)
- amazon-ec2 - 我们可以在 boto3 中找到 AWS 实例的根卷吗?
- python - Why is Hello printed only two times?
- java - 使用 okhttp 请求 POST 时如何避免出现验证码错误
- python-3.x - (Tkinter) 如何在 GUI 中显示时间而不发生重复?
- python - 将数据从 Oracle 数据库导入 Pandas 时出现 ORA-00942