加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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
程序应该打印..元素:1 5,出现次数应为1

到目前为止,我打印出最多的事件,只打印出一个元素.

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);
    }

}

效率不是很高,但它完成了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读