327. Count of Range Sum(divide and conquer)

1. Description

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:

Given nums = [-2, 5, -1], lower = -2, upper = 2,
Return 3.
The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 

2.


2. Analysis

题目的意思是找出这样符合条件的子区间的数目,这样的子区间需要满足区间内的元素之和在给定区间[lower, upper]之内。简单粗暴的方法当然是穷举完所有的可能子区间再判断计算。


3. code

naive solution , time complexity is O(n2)

class Solution {
public:
    int countRangeSum(vector<int>& nums, int lower, int upper) {

        long int sum = 0, tmp = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(lower <= nums[i] && nums[i] <= upper) {
                sum++;

            }

            tmp = nums[i];

            for(int j = i+1; j < nums.size(); j++) {
                tmp += nums[j];
                if(lower <= tmp && tmp <= upper) {
                    sum++;
                }

            }
        }
        return sum;
    } 
};

better solution, time complexity is


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值