0
点赞
收藏
分享

微信扫一扫

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


编写一个静态方法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 条评论