算法4-1.1.15编写一个静态方法histogram()

该篇博客介绍了如何编写一个静态方法histogram(),通过HashMap实现快速统计整数数组a[]中每个整数在0到M-1范围内出现的次数,确保数组元素之和等于输入数组长度。方法利用了哈希映射的高效查找特性,提高了计数效率。
摘要由CSDN通过智能技术生成

编写一个静态方法histogram(),接受一个整型数组a[]和一个整数M为参数并返回一个大小为M的数组,其中第i个元素的值为整数i在参数数组中出现的次数。如果a[]中的值均在0到M-1之间,返回数组中所有元素之和应该和a.length相等

import edu.princeton.cs.algs4.StdRandom;

import java.util.HashMap;
import java.util.Map;

public class Main {
    /**
     * 生成数组
     * @param N 数组大小
     * @param M 数组值范围在0--M-1
     * @return
     */
    public static int[] histogram(int N, int M){
        int[] b = new int[M];
        while (true){
            int[] a = new int[N];
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < N; i ++){
                a[i] = StdRandom.uniform(M);
                if (map.containsKey(a[i])){
                    map.put(a[i],map.get(a[i])+1);
                }else {
                    map.put(a[i],1);
                }
            }
            int total = 0;
            for (Map.Entry entry : map.entrySet()){
                b[(int)entry.getKey()]=(int)entry.getValue();
                total += (int)entry.getValue();
            }
            for (int value : b) {
                System.out.print(value + " ");
            }
            System.out.println();
            if (total == N) break;
        }
        return b;
    }

    public static void main(String[] args) {
        int[] b = histogram(12,10);
        for (int value : b) {
            System.out.print(value + " ");
        }
        //int[] b = histogram(a, M);
//        for (int i = 0; i < b.length; i ++){
//            System.out.println(i+","+b[i]);
//        }
    }
}

答案

1 1 2 1 1 0 1 4 1 0 
1 1 2 1 1 0 1 4 1 0 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值