找出一个数组中重复次数最多的字符暨找出Map中的最大Value及其对应的Key
2016-06-15 21:19
801 查看
rt:找出Map中的最大Value及其对应的Key,常用于找出一个数组中重复次数最多的字符
输出:
3 14
找出一个数组中出现最多次数的字符:
import java.util.*;
public class Inputmany {
public static void max(Map<Character, Integer> mp) {
char maxKey = '#';
int maxValue = 0;
Iterator it = mp.entrySet().iterator();// 将mp的键值对通过迭代器赋给it////////
while (it.hasNext()) {// 当it不为空的时候,将it赋给Map。Entry型的对象e///////
Map.Entry<Character, Integer> e = (Map.Entry) it.next();////////
if (e.getValue() > maxValue) {// 当前e的value大于maxValue时
maxValue = e.getValue();
maxKey = e.getKey();
}
}
System.out.println(maxKey + " " + maxValue);// 打印出最大的Value对应的Key和Value值
}
public static void main(String[] args) {
char[] array = { 'a', 's', 'd', 'f', 'a', 'a' };
Map mp = new HashMap();
for (int i = 0; i < array.length; i++) {
if (mp.containsKey(array[i])) {
mp.put(array[i], (int) mp.get(array[i]) + 1);
} else {
mp.put(array[i], 1);
}
}
max(mp);
}
}
输出:
a 3
import java.util.*; public class KeyOnMaxValue{ public static void main(String[] args) { Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); int maxKey = 0; int maxValue = 0; mp.put(2, 13); mp.put(3, 14); mp.put(4, 10); Iterator it = mp.entrySet().iterator();// 将mp的键值对通过迭代器赋给it while (it.hasNext()) {// 当it不为空的时候,将it赋给Map。Entry型的对象e Map.Entry<Integer, Integer> e = (Map.Entry) it.next(); if (e.getValue() > maxValue) {// 当前e的value大于maxValue时 maxValue = e.getValue(); maxKey = e.getKey(); } } System.out.println(maxKey + " " + maxValue);// 打印出最大的Value对应的Key和Value值 } }
输出:
3 14
找出一个数组中出现最多次数的字符:
import java.util.*;
public class Inputmany {
public static void max(Map<Character, Integer> mp) {
char maxKey = '#';
int maxValue = 0;
Iterator it = mp.entrySet().iterator();// 将mp的键值对通过迭代器赋给it////////
while (it.hasNext()) {// 当it不为空的时候,将it赋给Map。Entry型的对象e///////
Map.Entry<Character, Integer> e = (Map.Entry) it.next();////////
if (e.getValue() > maxValue) {// 当前e的value大于maxValue时
maxValue = e.getValue();
maxKey = e.getKey();
}
}
System.out.println(maxKey + " " + maxValue);// 打印出最大的Value对应的Key和Value值
}
public static void main(String[] args) {
char[] array = { 'a', 's', 'd', 'f', 'a', 'a' };
Map mp = new HashMap();
for (int i = 0; i < array.length; i++) {
if (mp.containsKey(array[i])) {
mp.put(array[i], (int) mp.get(array[i]) + 1);
} else {
mp.put(array[i], 1);
}
}
max(mp);
}
}
输出:
a 3
相关文章推荐
- POJ 2785-4 Values whose Sum is 0(a+b+c+d=0-折半枚举)
- Anroid UI
- C#实现的 快速查找通用组件 YHSoft.QuickFind
- Leetcode 347. Top K Frequent Elements
- Packet for query is too large
- N-Queens II
- 关于UIView位置信息的总结和CATransform3D初步认识
- 百度富文本编辑器UEditor的使用和他的图片上传
- Arduino串口高级用法
- Unique Paths II
- Unique Paths
- 232. Implement Queue using Stacks 还不理解法一
- 多线程更新UI的常用方法
- iOS学习之UINavigationController详解与使用(一)添加UIBarButtonItem
- Lightoj 1012 - Guilty Prince
- iOS UITextField的边框设置颜色的小坑
- IOS开发UIBarButtonItem-添加自定义Left或者Right按钮
- Codeforces 678F Lena and Queries
- Finished with non-zero exit value *
- UIViewController生命周期