我正在尝试在数组E中找到频率最高的数字和频率最低的重复数字
[7、5、6、4、6、5、5、8、7、0、7、5、2、9、7、9、3、4、6]
这些是上面数组中的重复编号:
“ 7”和“ 5”是最常见的数字, “ 4”是最不常见的重复项。
当我尝试编码时,我能够得到数字7,但是后来我不知道如何实现最少的频率。
这是我写的代码:
String[] numbers = "7564655870752979346".split("");
String elements = "";
int count = 0;
for (String tempElement : numbers) {
int tempCount = 0;
for (n = 0; n < numbers.length; n++) {
if (numbers[n].equals(tempElement)) {
tempCount++;
if (tempCount > count) {
elements = tempElement;
// System.out.println(elements);
count = tempCount;
}
}
}
}
System.out.println("Frequent number is: " + elements + " It appeared " + count+" times");
我上面的解决方案仅打印出7,而且我不知道如何检查最少重复项。
答案 0 :(得分:1)
写一个函数来查找最小重复数(从2开始)
public static String findMin(String[] numbers, int counter) {
int count = 0;
String elements = "";
for (String tempElement : numbers) {
int tempCount = 0;
for (int n = 0; n < numbers.length; n++) {
if (numbers[n].equals(tempElement)) {
tempCount++;
if (tempCount > counter) {
count = 0;
break;
}
if (tempCount > count) {
elements = tempElement;
// System.out.println(elements);
count = tempCount;
}
}
}
if(count == counter) {
return elements;
}
}
if(count < counter) {
return "";
}
return elements;
}
循环遍历数字
String x = "";
int c = 2;
do {
x = findMin(numbers, c ++);
} while(x == "");
整个代码将是
public class X {
public static String findMin(String[] numbers, int counter) {
int count = 0;
String elements = "";
for (String tempElement: numbers) {
int tempCount = 0;
for (int n = 0; n < numbers.length; n++) {
if (numbers[n].equals(tempElement)) {
tempCount++;
if (tempCount > counter) {
count = 0;
break;
}
if (tempCount > count) {
elements = tempElement;
// System.out.println(elements);
count = tempCount;
}
}
}
if (count == counter) {
return elements;
}
}
if (count < counter) {
return "";
}
return elements;
}
public static void main(String[] args) {
String[] numbers = "756655874075297346".split("");
String elements = "";
int count = 0;
for (String tempElement: numbers) {
int tempCount = 0;
for (int n = 0; n < numbers.length; n++) {
if (numbers[n].equals(tempElement)) {
tempCount++;
if (tempCount > count) {
elements = tempElement;
// System.out.println(elements);
count = tempCount;
}
}
}
}
String x = "";
int c = 2;
do {
x = findMin(numbers, c++);
} while (x == "");
System.out.println("Frequent number is: " + elements + " It appeared " + count + " times");
System.out.println("Min Frequent number is: " + x + " It appeared " + (c - 1) + " times");
}
}
答案 1 :(得分:0)
解决方案:
实施...是您要做的。但是,您将需要找到一种将包含一位数字的String
转换为整数的方法。 (提示:搜索javadocs!)