LintCode "Subarray Sum II"

Sliding window doesn't work. So it is a typical partial_sum base solution. As below. However if you use a balanced binary search tree, you can get O(nlgn) - like std::set<int>

class Solution {
public:
    /**
     * @param A an integer array
     * @param start an integer
     * @param end an integer
     * @return the number of possible answer
     */
    int subarraySumII(vector<int>& A, int start, int end) {
        size_t len = A.size();
        
    vector<int> presum(len + 1);
    std::partial_sum(A.begin(), A.end(), presum.begin() + 1);
    
        int ret = 0;
        for(int i = 1; i <= len; i ++)
        {
            for(int j = 0; j < i; j++)
            {
                int diff = presum[i] - presum[j];
                if(diff<=end && diff>=start)
                    ret ++;
            }
        }
        return ret;
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/4890836.html