我是新手,如果你在命令行输入6 6 6 1 4 4 4,我的代码给出最频繁的只有6,我需要它打印6和4我觉得那里应该是我的代码中的另一个循环
public class MostFrequent {
//this method creates an array that calculates the length of an integer typed and returns
//the maximum integer...
public static int freq(final int[] n) {
int maxKey = 0;
//initiates the count to zero
int maxCounts = 0;
//creates the array...
int[] counts = new int[n.length];
for (int i=0; i < n.length; i++) {
for (int j=0; j < n[i].length; j++)
counts[n[i][j]]++;
if (maxCounts < counts[n[i]]) {
maxCounts = counts[n[i]];
maxKey = n[i];
}
}
return maxKey;
}
//method mainly get the argument from the user
public static void main(String[] args) {
int len = args.length;
if (len == 0) {
//System.out.println("Usage: java MostFrequent n1 n2 n3 ...");
return;
}
int[] n = new int[len + 1];
for (int i=0; i<len; i++) {
n[i] = Integer.parseInt(args[i]);
}
System.out.println("Most frequent is "+freq(n));
}
}
...谢谢enter code here
答案 0 :(得分:0)
虽然这可能不是一个完整的解决方案,但这是一个建议。如果你想返回多个值,你的方法应该返回一个数组,或者更好的是,返回一个ArrayList(因为你不知道会有多少个频繁的数字)。在该方法中,您可以将每个最常请求的数字添加到列表中。
public static ArrayList<Integer> freq(final int[] n) {
ArrayList<Integer> list = new ArrayList<>();
...
if (something)
list.add(thatMostFrequentNumber)
return list;
}
答案 1 :(得分:0)
解决方案如下:
// To use count sort the length of the array need to be at least as
// large as the maximum number in the list.
int[] counts = new int[MAX_NUM];
for (int i=0; i < n.length; i++)
counts[n[i]]++;
// If your need more than one value return a collection
ArrayList<Integer> mf = new ArrayList<Integer>();
int max = 0;
for (int i = 0; i < MAX_NUM; i++)
if (counts[i] > max)
max = counts[i];
for (int i = 0; i < MAX_NUM; i++)
if (counts[i] == max)
mf.add(i);
return mf;
答案 2 :(得分:0)
您可以使用HashTable类轻松完成此操作。
第1部分。计算出每个数字的频率。
你可以通过HashTable或只是一个简单的数组来做到这一点,如果你的数字是整个numbrs并且有足够的上限。
第2部分。找到重复的频率。
您可以只做一个简单的for循环来确定哪些数字重复多次,然后相应地打印它们。这不一定会按顺序给你,所以你可以在第一遍中存储信息,然后相应地打印出来。您可以使用HashTable<Integer,ArrayList<Integer>
。使用密钥存储频率,使用ArrayList存储该频率范围内的数字。
如果你只想打印出频率最高的东西,你可以在插入我们的HashTable时保持“最大”。
答案 3 :(得分:0)
这是处理此问题的另一种方法。首先对列表进行排序,然后循环并跟踪最大的数字:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int n[] = { 6, 4, 6, 4, 6, 4, 1 };
List<Integer> maxNums = new ArrayList<Integer>();
int max = Integer.MIN_VALUE;
Integer lastValue = null;
int currentCount = 0;
Arrays.sort(n);
for( int i : n ){
if( lastValue == null || i != lastValue ){
if( currentCount == max ){
maxNums.add(lastValue);
}
else if( currentCount > max ){
maxNums.clear();
maxNums.add(lastValue);
max = currentCount;
}
lastValue = i;
currentCount = 1;
}
else {
currentCount++;
}
System.out.println("i=" + i + ", currentCount=" + currentCount);
}
if( currentCount == max ){
maxNums.add(lastValue);
}
else if( currentCount >= max ){
maxNums.clear();
maxNums.add(lastValue);
}
System.out.println(maxNums);
}
}
您可以尝试:http://ideone.com/UbmoZ5