首页 > 解决方案 > 计算给定整数元素数组中范围 * {0, ..., r} 中整数的出现次数

问题描述

出于某种原因,我的解决方案并不完整。我从隐藏的规格测试中得到 83/100。

我的解决方案有什么问题?可能有一个我没有想到的用例。

附加信息:

实现一个 count 方法,给定一个整数元素数组,返回另一个数组,其中包含输入数组中每个整数 {0, ..., r} 的出现次数,其中 r 是一个整数,用于显示整数元素的上边界您需要计算的整数。

返回的计数数组大小为 r + 1,其中每个索引 i 处的元素对应于整数 i 的出现次数(其中 i 在 {0, ..., r} 中)。

可以忽略输入数组中从 0 到 r 的整数范围之外的元素。

例如,给定输入 [0, 8, 1, 3, 1, 3, 10, 3] 且 r 为 4,则输出应为 [1, 2, 0, 3, 0]。

如果输入数组为 null 或长度为 0,则返回 null。

空间要求:方法 count 应该只为 count 数组使用额外的空间。

时间要求:计数应在输入数组中单次计算。

public class CountRepetitions {

    /**
     * Calculates the number of occurrences of integers from the range
     * {0, ..., r} within a given array of integer elements. Returns
     * the array of counts: a new array of integers of size r + 1, where the
     * element at index i denotes the number occurrences of elements equal
     * to i in the given input array (with i in {0, ..., r}).
     * If the input array is null or of length 0, this will return null.
     *
     * @param arr the array of integer elements to be counted.
     * @param r   the integer indicating the last element of the range.
     * @return a new array containing the number of occurrences of each
     * integer {0, ..., r} in the input array (index i has the
     * count of elements equal to i in the input array, with i
     * in {0, ..., r})
     */
    public static int[] count(int[] arr, int r) {
        // Exceptional cases
        // 1. If the input array is null or of length 0, this will return null.
        if (arr == null || arr.length == 0) return null;

        // Normal case
        int[] result = new int[r + 1];
        for (int x : arr) if (x >= 0 && x < r) result[x]++;
        return result;
    }

标签: javaalgorithm

解决方案


如果 (x >= 0 && x <= r )

还要确保检查 r >= 0。


推荐阅读