算法(第4版本)1.1.15

来源:互联网 发布:妙味jquery源码分析 编辑:程序博客网 时间:2024/06/07 22:02


    这道题没有答案,不知道下面这样写有没有达到要求 


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

private static void test15(){    int a[] = {4, 4, 2, 3, 2, 4, 5, 6, 6};    int result[] = new int[6];    int max = result.length;    int length = a.length;    HashMap<String, Integer> tempMap = new HashMap<>();    int value;    String key;    for(int i = 0; i < length ; i++){        key = String.valueOf(a[i]);        if(tempMap.containsKey(key)){            value = tempMap.get(key) + 1;        } else{            value = 1;        }        if(a[i] < max){          result[a[i]] = value;        }        tempMap.put(key, value);    }    for(int i = 0; i < max; i++){        System.out.print(result[i] + ", ");    }}


刚刚在网上看到别人的方法,瞬间一万点伤害,觉得自己是猪脑袋 http://blog.csdn.net/forTHQ/article/details/51462118

private static void test1502(){    int a[] = {4, 4, 2, 3, 2, 4, 5, 6, 6};    int result[] = new int[6];    int max = result.length;    int length = a.length;    for(int i = 0; i < length; i++){        if(a[i] < max){            result[a[i]]++;        }    }    for(int i = 0; i < max; i++){        System.out.print(result[i] + ", ");    }}


0 0
原创粉丝点击