1. 程式人生 > 其它 >區間和的個數

區間和的個數

給你一個整數陣列nums 以及兩個整數lower 和 upper 。求陣列中,值位於範圍 [lower, upper] (包含lower和upper)之內的 區間和的個數 。

區間和S(i, j)表示在nums中,位置從i到j的元素之和,包含i和j(i ≤ j)。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/count-of-range-sum
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class Solution {
    public static int countRangeSum(int[] nums, int lower, int upper) {
        long[] sum = new long[nums.length + 1];
        for (int i = 1; i <= nums.length; ++i) {
            sum[i] = sum[i - 1] + nums[i - 1];
        }
        return solveWhileMergeSort(sum, 0, sum.length - 1, lower, upper);
    }

    private static int solveWhileMergeSort(long[] sum, int L, int R, int lower, int upper) {
        if (L == R) {
            return 0;
        }
        int mid = (L + R) >> 1;
        int ret = solveWhileMergeSort(sum, L, mid, lower, upper) + solveWhileMergeSort(sum, mid + 1, R, lower, upper);

        int left = mid + 1, right = mid + 1;
        int i = L;
        while (i <= mid) {
            while (left <= R && sum[left] - sum[i] < lower) {
                left++;
            }
            while (right <= R && sum[right] - sum[i] <= upper) {
                right++;
            }
            i++;
            ret += (right - left);
        }

        int p1 = L, p2 = mid + 1;
        int index = 0;
        long[] helper = new long[R - L + 1];
        while (p1 <= mid && p2 <= R) {
            if (sum[p1] <= sum[p2]) {
                helper[index++] = sum[p1++];
            } else {
                helper[index++] = sum[p2++];
            }
        }

        while (p1 <= mid) {
            helper[index++] = sum[p1++];
        }

        while (p2 <= R) {
            helper[index++] = sum[p2++];
        }

        System.arraycopy(helper, 0, sum, L, helper.length);

        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {0};
        int lower = 0;
        int upper = 0;
        System.out.println(countRangeSum(nums, lower, upper));
    }
}
心之所向,素履以往 生如逆旅,一葦以航