众数问题
来源:互联网 发布:java什么是敏捷性开发 编辑:程序博客网 时间:2024/04/24 01:42
import java.util.HashMap;
import java.util.Scanner;
public class Section2_1 {
/**
* TODO
*
* @version 2013-9-11 下午7:08:34
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入多重集合的元素个数");
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
Mode m = new Mode();
System.out.println(m.result(m.findMode(arr), arr));
}
}
class Mode {
/**
* 将数字与其出现的次数用键值对的形式存放
* @version 2013-9-12 上午12:28:51
*/
public HashMap<Integer, Integer> findMode(int[] arr) {
HashMap<Integer, Integer> map=new HashMap<Integer, Integer>();
for(int i=0;i<arr.length;i++){
if(this.isexsit(arr[i],map)){//如果该数存在于map中就返回true并对值(次数)进行
map.put(arr[i], map.get(arr[i])+1);
}else{
map.put(arr[i], 1);//否则新添入一个键值对
}
}
return map;
}
/**
* 检验该数在map中是否存在
* @version 2013-9-12 上午12:26:21
*/
public boolean isexsit(int a,HashMap<Integer, Integer>map){
if(map.size()==0){
return false;
}else{
return map.containsKey(a);
}
//return map.size()==0?false:map.get(a)!=0;
}
public String result(HashMap<Integer, Integer> map,int []arr) {
int [] mode =new int[10];// 众数存放使用的数组
int num = 0;// 重数
int temp=0;//为避免数组在遍历时重复的值多次进入循环,用来存放上一次进入循环时的arr[i]的值
int index=0;//数组的下标
int max=0;
String s="众数为:";
for (int i = 0; i < arr.length; i++) {
while(temp!=arr[i]){
max=map.get(arr[i]);
if(num<=max){
if(num<max){
num=max;
mode[0]=arr[i];//用数组的第一个位置来存放第一个出现的众数的值
}
else if(num==max){
index++;
mode[index]=arr[i];//用以后的空间来存放可能出现的多个众数的值
}
}
temp=arr[i];
}
}
for(int j=0;j<mode.length&&mode[j]!=0;j++){//只遍历有效空间内的值
s=s.concat(Integer.toString(mode[j])+" &");
}
return s + "重数为:" + num;
}
}
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- 众数问题
- iOS开发基础之iOS响应者链
- 使用WebView实现新浪微博Oauth2.0认证(android)
- wpf带checkbox的treeview开发
- Oauth认证-新浪微博开发(上)
- 3 ways to run Java main from Maven
- 众数问题
- Oauth认证-新浪微博开发(下)
- { 数学 }hdoj1290
- windows下eclipse中,涉及源码编译的apk开发——使用系统签名机制解决方法
- 米粉和移动发烧友俱乐部不同的结局
- 在字符串中找出连续最长的数字串,并把这个串的长度返回
- 在应用中利用webview加载网页引起的内存高消耗
- iOS 之tableView反弹的问题
- Linux系统新手学习的11点建议