给定一个整数数组,其中元素的取值范围为0到10000,求其中出现次数最多的数
来源:互联网 发布:数据库管理系统语言 编辑:程序博客网 时间:2024/04/30 06:17
我的菜菜解法:
//给定一个整数数组,其中元素的取值范围为0到10000,求其中出现次数最多的数
public class Count{
public static void main(String args[]){
int array[] = {1,23,1,222,3,1,2,2,22,355,121,23,23,23,23,23,22,22,22,3,4};
long start = System.nanoTime();
int arr[] = new int[array.length];
/*数组默认值为零
for(int i = 0; i<arr.length;i++){
arr[i] = 0;
}*/
for(int i = 0; i<array.length;i++){
for(int j = i+1;j<array.length; j++){
if(array[i] == array[j]){
arr[j]++;
}
}
}
System.out.println("计数数组:");
for(int i = 0;i<arr.length;i++){
System.out.print(arr[i] + " ," );
}
int max = arr[0];
int index = 0;
for(int i =1; i<arr.length; i++){
if(arr[i]>=max){
max = arr[i];
index = i;
}
}
System.out.println();
System.out.println("出现最多的数:" + array[index]);
long end = System.nanoTime();
System.out.println("耗时:" + (end-start) +"ns");
}
}
牛逼解法:
public class Count2 {
public static void main(String[] args) {
int[] count = new int[10001];
int array[] = {1,23,1,222,3,1,2,2,22,355,121,23,23,23,23,23,22,22,22,3,4};
long start = System.nanoTime();
/* for(int num : array){
count[num]++;
}
*/
for(int num=0;num<array.length;num++){
count[array[num]]++;
}
int max = -1;
int loc = -1;
for (int i = 0;i<count.length;i++) {
if (max < count[i]) {
loc = i;
System.out.println(i);
max = count[i];
}
}
System.out.println(loc);
long end = System.nanoTime();
System.out.println(end-start);
for(int n:count){
System.out.print("."+count[n]);
}
}
}
- 给定一个整数数组,其中元素的取值范围为0到10000,求其中出现次数最多的数
- C++ - 一个非递减数组,下标从0到n,元素的取值范围为从0到n的整数,判断其中是否有重复元素
- 求一个数组中重复元素出现最多值,最大的元素及出现次数,次数相同时,取最大值,优先考虑次数
- 给定一个整数,求其二进制数中1的个数
- 给定一个正整数组(最多1024个数,数组输入以0结束 ),求出现次数最多的数
- 统计一个无序数组中出现次数最多的元素
- 统计一个无序数组中出现次数最多的元素
- 求一个数组中出现次数最多的数
- 求一个数组中出现次数最多的数
- 给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。
- 数组中出现次数最多的数及出现次数
- 取值为[1,n-1] 含n 个元素的整数数组至少存在一个重复数,O(n) 时间内找出其中任意一个重复数
- hdu 1806 Frequent values(给定一个非降序数组,求任意区间内出现次数最多的数的次数)
- 求整数序列中出现次数最多的数
- 查找一个数组中出现次数最多的值(长度为1000)
- 数组-10. 求整数序列中出现次数最多的数(15)
- 数组-10. 求整数序列中出现次数最多的数
- 数组-10. 求整数序列中出现次数最多的数(15)
- 国外SEO操作流程图
- 转:如何选择 Excel 中的数据列,然后将数据粘贴到文本文件中?
- QT4 一个简单的打开文件功能
- 爬虫crawler和查询searcher
- oracle服务进程
- 给定一个整数数组,其中元素的取值范围为0到10000,求其中出现次数最多的数
- cleversafe 的读写机制分析与编解码接口
- Linux命令整理
- Hibernate FAQ - Collection
- Media Foundation Programming--Image Stride
- Android游戏开发框架LGame-Android-0.2.5R发布
- solr的详细安装方法
- VB 写COOKIE
- 网站诊断报告