327. Count of Range Sum

在这里插入图片描述

少有的一道自己很快做出来,没有错误的hard题目,可喜可贺。。。
方法一:
第一反应就是前缀和:

class Solution {
public:
    int countRangeSum(vector<int>& nums, int lower, int upper) {
        int sz = nums.size();
        if (sz == 0)
            return 0;
        map<long long, int> preSumCnts;
        preSumCnts[0] = 1;
        long long preSum = 0;
        int retCnt = 0;
        for (int i = 0; i < sz; ++i) {
            preSum += nums[i];
            auto lowIter = preSumCnts.lower_bound(preSum - upper);
            auto upIter = preSumCnts.upper_bound(preSum - lower);
            while (lowIter != upIter) {
                retCnt += (*lowIter).second;
                ++lowIter;
            }
            preSumCnts[preSum]++;
        }
        return retCnt;
    }
};
//要考虑溢出

方法二:
看评论区的时候很惊讶没有多少人使用这个方法,可能是C++ map提供的upper_bound 和 lower_bound其他语言没有??
所以考虑其他的解法。
评论区有个分治(归并排序)的做法,暂时没有看明白,之后再看吧补充上来(毕竟现在最重要的是准备面试:)

posted @ 2019-10-03 21:09  于老师的父亲王老爷子  阅读(11)  评论(0)    收藏  举报