首页 > 其他 > 详细

LintCode "Subarray Sum II"

时间:2015-10-19 07:08:08      阅读:259      评论:0      收藏:0      [点我收藏+]

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

 

LintCode "Subarray Sum II"

原文:http://www.cnblogs.com/tonix/p/4890836.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!