Java.Algo.CumulativeApproach

for tasks like “find count nums less than current in array”

build frequency array

build cumulative array

count result

    public int[] smallerNumbersThanCurrent(int[] nums) {
        final int kMax = 100;
        int[] ans = new int[nums.length];
        int[] count = new int[kMax + 1];

        // frequency
        for (final int num : nums)
            ++count[num];

        // cumulative frequency
        for (int i = 1; i <= kMax; ++i)
            count[i] += count[i - 1];

        // result
        for (int i = 0; i < nums.length; ++i)
            ans[i] = nums[i] == 0 ? 0 : count[nums[i] - 1];

        return ans;
    }
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.