327. Count of Range Sum

本文介绍了一种高效的算法来统计数组中所有子数组的和落在指定范围内的数量。通过使用C++ STL中的multiset进行排序和查找操作,实现了比朴素算法更好的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.

Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.

Example:

Input: nums = [-2,5,-1], lower = -2, upper = 2,
Output: 3 
Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2.

Firstly, we calculate the littlesum[i], which means the sum of the elements from index 0 to index i.
Based on above operations, we can get the sum S[i, j] of elements in the range [i, j] by littlesum[j] - littlesum[i - 1].
Now we want to get the count of (i, j) which make lower <= S[i, j] <= upper.
The naive solution we can think of is a O(n^2) solution, we get thought all pair of i and j, then compare S[i, j] with lower and upper.
But the question tell us we must do beter than that.
Here is a interesting solution using STL.
Put all the elements of littlesum into a multiset and they will be sorted automatically, then we pass through the set, for every element A, we find lower_bound(A - upper) and A - lower.

int countRangeSum(vector<int>& nums, int lower, int upper)
{
    int result = 0;
    long long sum = 0;
    multiset<long long> st;
    /*
    Firstly, we insert 0 into st, it means itself, for example, we are dealing this situation where sum = 3 and i = 5, 
    and the lower is 2, the upper is 4, it's clear that the range [0, 5] is one of the right answers, and we can't get it by littlesum[i] - littlesum[j] (i >= 0, j >= 0) except littlesum[j] equals 0.
    so, we insert 0 into st firstly, sum with index i minus 0 means sum itself.
    */
    st.insert(0);
    //In case of duplicate addition of result, we do distance() once we put sum into the st, which means we just choose appropriate littesum[j] whose j is smaller than or same as i.
    for(int i = 0; i < nums.size(); i++)
    {
        sum += nums[i];
        //And the range of [i, j] is at least 1, so we insert sum into st after distance().
        result += distance(st.lower_bound(sum - upper), st.upper_bound(sum - lower));
        st.insert(sum);
    }
    return result;
}

www.sunshangyu.top

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值