作业帮 > 综合 > 作业

java 数组 急example:maxOccurence({1,3,7,2,1,2,5,1})={1,3}maxOcc

来源:学生作业帮 编辑:百度作业网作业帮 分类:综合作业 时间:2024/07/17 16:51:48
java 数组 急
example:maxOccurence({1,3,7,2,1,2,5,1})={1,3}
maxOccurence({1,3,7,2,1,2,5,1,2,5,5})={5,3}
根据这两个写出方法maxOccurence!
这个题目的意思是 新建立一个大小为2的数组,例如a[2].
a[0]等于出现最频繁的数,并且如果两个数出现的频率一样,比较两个数的大小,大的放入a[0].a[1]等于出现最频繁数出现的次数!
java 数组 急example:maxOccurence({1,3,7,2,1,2,5,1})={1,3}maxOcc
你的要求我没有明白,如果是想取出一个数组中出现次数最多的数字,那么你给的例子的结果不正确啊.
例如:
maxOccurence({1,3,7,2,1,2,5,1,2,5,5})的返回值如果表示出现次数最多的项目,那结果应该是{1,2,5},不过我也没有根据你的例子猜测出你的函数意图.
下面是我假设你要获取一个数组中出现次数最多的项目(使用了泛型).
public Collection maxOccurence(T[] array) {

Map counts = new HashMap();
for (T item : array) {
Integer count = counts.get(item);
if (count == null) {
count = 0;
}
counts.put(item, ++count);
}

int maxOccurs = 1;
Set maxArray = new HashSet();
Set keys = counts.keySet();
for (T key : keys) {
Integer count = counts.get(key);
if (count > maxOccurs) {
maxOccurs = count;
maxArray.clear();
maxArray.add(key);
} if (count == maxOccurs) {
maxArray.add(key);
}
}

return maxOccurs == 1 ? Arrays.asList(array) : maxArray;
}
补充问题的时候,没有通知我,所以修改答案晚了,下面是按照你的要求修改后的代码.
public int[] maxOccurence(int[] array) {

Map counts = new HashMap();
for (Integer item : array) {
Integer count = counts.get(item);
if (count == null) {
count = 0;
}
counts.put(item, ++count);
}

int maxOccurs = 1;
Integer maxValue = array[0];
Set keys = counts.keySet();
for (Integer key : keys) {
Integer count = counts.get(key);
if (count >= maxOccurs) {
maxOccurs = count;
if (key > maxValue) {
maxValue = key;
}
}
}

int[] result = new int[2];
result[0] = maxValue;
result[1] = maxOccurs;
return result;
}