Java – 打印出数组中发生最少的元素
发布时间:2020-12-15 04:17:25 所属栏目:Java 来源:网络整理
导读:我得到一个大小为10的数组,我想编写一个程序,打印出发生次数最少的元素和它们出现的次数. 例如对于阵列:1 2 3 3 2 2 4 4 5 4 程序应该打印..元素:1 5,出现次数应为1 到目前为止,我打印出最多的事件,只打印出一个元素. public class Question3 { public sta
我得到一个大小为10的数组,我想编写一个程序,打印出发生次数最少的元素和它们出现的次数.
例如对于阵列:1 2 3 3 2 2 4 4 5 4 到目前为止,我打印出最多的事件,只打印出一个元素. public class Question3 { public static void main (String[] args) { int[] testarray = {1,2,3,4,5,4}; int count = 0; int bigCount = 10; for (int i=0; i < array.length; i++) { for (int j=0; j < array.length; j++) { if(array[j] == array[i]) { count++; } } if(count > bigCount) { bigCount = count; array[i] = random; } } System.out.println("num of elements and occurences: " + maxCount); } } 解决方法
你需要一个数据结构来保存每个独特的元素,它的数量,Map< Integer,Integer>可能是你最好的选择.像你现在一样迭代你的数组,并保持计数.像这样的东西:
public static void main(String[] args) { int[] array = {1,4}; //create the map like this: <Element,Count> Map<Integer,Integer> counts = new HashMap<>(); for (Integer i : array) { if (counts.get(i) == null) { counts.put(i,1); } else { counts.put(i,counts.get(i) + 1); } } //find min value by sorting values and taking top element List<Integer> cs = new ArrayList<Integer>(counts.values()); Collections.sort(cs); int minVal = cs.get(0); //find elements with minVal as their count List<Integer> minElements = new ArrayList<>(); for (Entry<Integer,Integer> entry : counts.entrySet()) { if (entry.getValue() == minVal) { minElements.add(entry.getKey()); } } //spit out each element and the count for (Integer i : minElements) { System.out.println("Element: " + i + " Number of occurences: " + minVal); } } 效率不是很高,但它完成了. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- java – 使用JAXB根据属性创建引用对象
- Spring Boot 使用WebAsyncTask异步返回结果
- 所有可能的两个向量的组合,同时保持R中的顺序
- java – 泛型和类<?扩展枚举<?>>,EnumSet.al
- JAVA 如何使用延迟
- java Bean与json对象间的转换实例讲解
- 如何在JAVA中的HttpURLConnection中发送PUT,DELETE HTTP请求
- JavaEE组件commons-fileupload实现文件上传、下载
- java – Performance Encog vs Deeplearning4J
- ExecutorService与invokeAll()和Future在java中
推荐文章
站长推荐
热点阅读