Leetcode - Count of Range Sum

My code:

public class Solution {
    public int countRangeSum(int[] nums, int lower, int upper) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int len = nums.length;
        long[] sums = new long[len + 1];
        for (int i = 1; i < sums.length; i++) {
            sums[i] = sums[i - 1] + nums[i - 1];
        }
        return mergesort(sums, 0, len, lower, upper);
    }
    
    private int mergesort(long[] sums, int start, int end, int lower, int upper) {
        if (start >= end) {
            return 0;
        }
        int mid = start + (end - start) / 2;
        int cnt = mergesort(sums, start, mid, lower, upper) + mergesort(sums, mid + 1, end, lower, upper);
        long[] cache = new long[end - start + 1];
        int k = mid + 1;
        int j = mid + 1;
        int r = mid + 1;
        int t = 0;
        for (int i = start; i <= mid; i++) {
            while (k <= end && sums[k] - sums[i] < lower) {
                k++;
            }
            while (j <= end && sums[j] - sums[i] <= upper) {
                j++;
            }
            while (r <= end && sums[r] <= sums[i]) {
                cache[t] = sums[r];
                t++;
                r++;
            }
            cache[t] = sums[i];
            t++;
            cnt += j - k;
        }
        
        while (r <= end) {
            cache[t] = sums[r];
            t++;
            r++;
        }
        
        for (int i = start; i <= end; i++) {
            sums[i] = cache[i - start];
        }
        return cnt;
    }
}

reference:
https://discuss.leetcode.com/topic/33738/share-my-solution/2

这道题目真的挺难的。我是在做了 count of number smaller after self 之后看这个解释,才有了思路。

首先就是一个累加和 sums, 这个都能理解。
然后开始merge sort
假设我们已经有了left and right part
left is sorted
right is sorted, too
left[start, mid], right[mid + 1, end]
我们需要找的是
i = start
k = mid + 1
j = mid + 1

sums[k] – sums[i] >= lower
sums[j] – sums[i] > upper

then
count += j – k

这是第一步

第二步,我们需要merge原数组
int[] cache = new int[end – start + 1];
int t = 0;
int r = mid + 1;
if (sums[r] <= sums[i]) {
cache[t++] = sums[r++];
}
cache[t] = sums[i];
t++;

最后的最后,千万记得,当 i > mid 结束循环时,
不代表 r 已经 > end 了,也就是说,merge可能并没有结束。
我们需要继续拷贝给 cache[]

题目真的,注意点太多了,太琐碎了。有时间再背一下把。

Anyway, Good luck, Richardo! — 10/09/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/d96a9573b48b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞