码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode "Subarray Sum II"

时间:2015-10-19 07:09:26      阅读:1302      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!