[LeetCode] 327. Count of Range Sum 區間和計數


 

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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

 

這道題給了我們一個數組,又給了一個下限和一個上限,讓求有多少個不同的區間使得每個區間的和在給定的上下限之間。這道題的難度系數給的是 Hard,的確是一道難度不小的題,題目中也說了 Brute Force 的方法太 Naive 了,只能另想方法了。To be honest,這題超出了博主的能力范圍,所以博主也沒掙扎了,直接上網搜大神們的解法啦。首先根據前面的那幾道類似題 Range Sum Query - MutableRange Sum Query 2D - Immutable 和 Range Sum Query - Immutable 的解法可知類似的區間和的問題一定是要計算累積和數組 sums 的,其中 sum[i] = nums[0] + nums[1] + ... + nums[i],對於某個i來說,只有那些滿足 lower <= sum[i] - sum[j] <= upper 的j能形成一個區間 [j, i] 滿足題意,目標就是來找到有多少個這樣的 j (0 =< j < i) 滿足 sum[i] - upper =< sum[j] <= sum[i] - lower,可以用 C++ 中由紅黑樹實現的 multiset 數據結構可以對其中數據排序,然后用 upperbound 和 lowerbound 來找臨界值。lower_bound 是找數組中第一個不小於給定值的數(包括等於情況),而 upper_bound 是找數組中第一個大於給定值的數,那么兩者相減,就是j的個數,參見代碼如下:

 

解法一:

class Solution {
public:
    int countRangeSum(vector<int>& nums, int lower, int upper) {
        int res = 0;
        long long sum = 0;
        multiset<long long> sums;
        sums.insert(0);
        for (int i = 0; i < nums.size(); ++i) {
            sum += nums[i];
            res += distance(sums.lower_bound(sum - upper), sums.upper_bound(sum - lower));
            sums.insert(sum);
        }
        return res;
    }        
};

 

我們再來看一種方法,這種方法的思路和前一種一樣,只是沒有 STL 的 multiset 和 lower_bound 和 upper_bound 函數,而是使用了 Merge Sort 來解,在混合的過程中,已經給左半邊 [start, mid) 和右半邊 [mid, end) 排序了。當遍歷左半邊,對於每個i,需要在右半邊找出k和j,使其滿足:

j是第一個滿足 sums[j] - sums[i] > upper 的下標

k是第一個滿足 sums[k] - sums[i] >= lower 的下標 

那么在 [lower, upper] 之間的區間的個數是 j - k,同時也需要另一個下標t,用來拷貝所有滿足 sums[t] < sums[i] 到一個寄存器 Cache 中以完成混合排序的過程,這個步驟是混合排序的精髓所在,實際上這個寄存器的作用就是將 [start, end) 范圍內的數字排好序先存到寄存器中,然后再覆蓋原數組對應的位置即可,(注意這里 sums 可能會整型溢出,使用長整型 long 代替),參見代碼如下:

 

解法二:

class Solution {
public:
    int countRangeSum(vector<int>& nums, int lower, int upper) {
        vector<long> sums(nums.size() + 1, 0);
        for (int i = 0; i < nums.size(); ++i) {
            sums[i + 1] = sums[i] + nums[i];
        }
        return countAndMergeSort(sums, 0, sums.size(), lower, upper);
    }
    int countAndMergeSort(vector<long>& sums, int start, int end, int lower, int upper) {
        if (end - start <= 1) return 0;
        int mid = start + (end - start) / 2;
        int cnt = countAndMergeSort(sums, start, mid, lower, upper) + countAndMergeSort(sums, mid, end, lower, upper);
        int j = mid, k = mid, t = mid;
        vector<int> cache(end - start, 0);
        for (int i = start, r = 0; i < mid; ++i, ++r) {
            while (k < end && sums[k] - sums[i] < lower) ++k;
            while (j < end && sums[j] - sums[i] <= upper) ++j;
            while (t < end && sums[t] < sums[i]) cache[r++] = sums[t++];
            cache[r] = sums[i];
            cnt += j - k;
        }
        copy(cache.begin(), cache.begin() + t - start, sums.begin() + start);
        return cnt;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/327

 

類似題目:

Range Sum Query - Mutable 

Range Sum Query 2D - Immutable

Range Sum Query - Immutable

Reverse Pairs

Count of Smaller Numbers After Self

 

參考資料:

https://leetcode.com/problems/count-of-range-sum/

https://leetcode.com/problems/count-of-range-sum/discuss/77990/Share-my-solution

https://leetcode.com/problems/count-of-range-sum/discuss/78006/Summary-of-the-Divide-and-Conquer-based-and-Binary-Indexed-Tree-based-solutions

https://leetcode.com/problems/count-of-range-sum/discuss/78030/8-line-multiset-C%2B%2B-solution-(100ms)-also-binary-search-tree-(180ms)-%2B-mergesort(52ms)

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM