LeetCode 327.Count of Range Sum

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:

Input: nums = [-2,5,-1], lower = -2, upper = 2,

Output: 3 

Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2.

分析:题目意思是统计处于【lower,upper】的区间和个数。

1.采用分治法,利用归并排序

class Solution {
public:
    int ans=0;
    int low, up;
    void merge(long long s[], int l, int m, int r) {
        int x=m+1,y=m+1;
        for(int z = l; z <= m; z++) {          
            while(x<=r&&s[x]-s[z]<low) x++;
            y=x;
            while(y<=r&&s[y]-s[z]<=up) y++;
            ans+=(y-x); 
        }
        long long t[10005]={0};
        int i = l, j = m+1, k=l;
        while(i<=m&&j<=r) {
            if(s[i]<=s[j]) t[k++]=s[i++];
            else t[k++]=s[j++]; 
        }
        while(i<=m) t[k++]=s[i++];
        while(j<=r) t[k++]=s[j++];
        for(int i = l; i <= r; i++) s[i]=t[i];
    }
    void solve(long long s[], int l, int r) {
        int m = l+(r-l)/2;
        if(l>=r) return;
        solve(s, l, m);
        solve(s, m+1, r);
        merge(s,l,m,r);
    }
    int countRangeSum(vector<int>& nums, int lower, int upper) {
        low = lower;
        up = upper;
        int len = nums.size();
        if(len==0) return 0;
        long long s[10005]={0};
        for(int i = 1; i <= len; i++) s[i] = s[i-1]+nums[i-1];   
        solve(s,0,len);
        return ans;
    }
};

  

 

转载于:https://www.cnblogs.com/promise123/p/10628604.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值