09-04-2015 Array
来源:互联网 发布:买大班模型 淘宝店 编辑:程序博客网 时间:2024/04/29 07:27
这是一道看似简单的题目。
BJP3 Exercise 7.5: mode
Write a method called mode
that returns the most frequently occurring element of an array of integers. Assume that the array has at least one element and that every element in the array has a value between 0
and 100
inclusive. Break ties by choosing the lower value.
For example, if the array passed contains the values {27, 15, 15, 11, 27}
, your method should return 15
. (Hint: You may wish to look at the Tally
program from earlier in this chapter to get an idea of how to solve this problem.)
我自己的答案,还对了,但是太多for loop了。
public static int mode(int[] arr) {
int max = 0;
int maxFreq = 0;
Arrays.sort(arr);
max = arr[arr.length-1];
int[] count = new int[max + 1];
for (int i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] > maxFreq) {
maxFreq = count[i];
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] == maxFreq) {
return i;
}
}
return -1;
}
- 09-04-2015 Array
- array
- Array#-
- Array#[]
- Array#<<
- Array
- array
- Array
- array
- Array
- array
- array
- array
- array()
- Array
- Array
- Array
- Array
- 统计一个字符串中某个字符第一次出现的位置和最后一次出现的位置
- zigbee按键IO口的修改
- 黑马程序员--C语言之复杂数据类型
- c++中容器元素都是副本
- 类模板与模板类的概念
- 09-04-2015 Array
- 让VC调试器正确显示UTF-8字符串
- Android中使用ListView实现漂亮的表格效果
- 链表反转
- 16进制颜色设定
- 改装LogitechK120为背光键盘
- Ajax实现在线聊天室
- 解决bringChildToFront/bringToFront不起作用的问题
- scp和sftp常用操作