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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

这道题给了我们一个数组,又给了一个下限和一个上限,让求有多少个不同的区间使得每个区间的和在给定的上下限之间。这道题的难度系数给的是 Hard,的确是一道难度不小的题,题目中也说了 Brute Force 的方法太 Naive 了,只能另想方法了。To be honest,这题超出了博主的能力范围,所以博主也没挣扎了,直接上网搜大神们的解法啦。首先根据前面的那几道类似题 Range Sum Query - MutableRange Sum Query 2D - Immutable 和 Range Sum Query - Immutable 的解法可知类似的区间和的问题一定是要计算累积和数组 sums 的,其中 sum[i] = nums[0] + nums[1] + ... + nums[i],对于某个i来说,只有那些满足 lower <= sum[i] - sum[j] <= upper 的j能形成一个区间 [j, i] 满足题意,目标就是来找到有多少个这样的 j (0 =< j < i) 满足 sum[i] - upper =< sum[j] <= sum[i] - lower,可以用 C++ 中由红黑树实现的 multiset 数据结构可以对其中数据排序,然后用 upperbound 和 lowerbound 来找临界值。lower_bound 是找数组中第一个不小于给定值的数(包括等于情况),而 upper_bound 是找数组中第一个大于给定值的数,那么两者相减,就是j的个数,参见代码如下:

解法一:

class Solution {
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
int res = ;
long long sum = ;
multiset<long long> sums;
sums.insert();
for (int i = ; i < nums.size(); ++i) {
sum += nums[i];
res += distance(sums.lower_bound(sum - upper), sums.upper_bound(sum - lower));
sums.insert(sum);
}
return res;
}
};

我们再来看一种方法,这种方法的思路和前一种一样,只是没有 STL 的 multiset 和 lower_bound 和 upper_bound 函数,而是使用了 Merge Sort 来解,在混合的过程中,已经给左半边 [start, mid) 和右半边 [mid, end) 排序了。当遍历左半边,对于每个i,需要在右半边找出k和j,使其满足:

j是第一个满足 sums[j] - sums[i] > upper 的下标

k是第一个满足 sums[k] - sums[i] >= lower 的下标

那么在 [lower, upper] 之间的区间的个数是 j - k,同时也需要另一个下标t,用来拷贝所有满足 sums[t] < sums[i] 到一个寄存器 Cache 中以完成混合排序的过程,这个步骤是混合排序的精髓所在,实际上这个寄存器的作用就是将 [start, end) 范围内的数字排好序先存到寄存器中,然后再覆盖原数组对应的位置即可,(注意这里 sums 可能会整型溢出,使用长整型 long 代替),参见代码如下:

解法二:

class Solution {
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
vector<long> sums(nums.size() + , );
for (int i = ; i < nums.size(); ++i) {
sums[i + ] = sums[i] + nums[i];
}
return countAndMergeSort(sums, , sums.size(), lower, upper);
}
int countAndMergeSort(vector<long>& sums, int start, int end, int lower, int upper) {
if (end - start <= ) return ;
int mid = start + (end - start) / ;
int cnt = countAndMergeSort(sums, start, mid, lower, upper) + countAndMergeSort(sums, mid, end, lower, upper);
int j = mid, k = mid, t = mid;
vector<int> cache(end - start, );
for (int i = start, r = ; i < mid; ++i, ++r) {
while (k < end && sums[k] - sums[i] < lower) ++k;
while (j < end && sums[j] - sums[i] <= upper) ++j;
while (t < end && sums[t] < sums[i]) cache[r++] = sums[t++];
cache[r] = sums[i];
cnt += j - k;
}
copy(cache.begin(), cache.begin() + t - start, sums.begin() + start);
return cnt;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/327

类似题目:

Range Sum Query - Mutable

Range Sum Query 2D - Immutable

Range Sum Query - Immutable

Reverse Pairs

Count of Smaller Numbers After Self

参考资料:

https://leetcode.com/problems/count-of-range-sum/

https://leetcode.com/problems/count-of-range-sum/discuss/77990/Share-my-solution

https://leetcode.com/problems/count-of-range-sum/discuss/78006/Summary-of-the-Divide-and-Conquer-based-and-Binary-Indexed-Tree-based-solutions

https://leetcode.com/problems/count-of-range-sum/discuss/78030/8-line-multiset-C%2B%2B-solution-(100ms)-also-binary-search-tree-(180ms)-%2B-mergesort(52ms)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Count of Range Sum 区间和计数的更多相关文章

  1. [LeetCode] 327. Count of Range Sum 区间和计数

    Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.Ra ...

  2. 327 Count of Range Sum 区间和计数

    Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.Ra ...

  3. LeetCode Count of Range Sum

    原题链接在这里:https://leetcode.com/problems/count-of-range-sum/ 题目: Given an integer array nums, return th ...

  4. 【算法之美】你可能想不到的归并排序的神奇应用 — leetcode 327. Count of Range Sum

    又是一道有意思的题目,Count of Range Sum.(PS:leetcode 我已经做了 190 道,欢迎围观全部题解 https://github.com/hanzichi/leetcode ...

  5. 327. Count of Range Sum

    /* * 327. Count of Range Sum * 2016-7-8 by Mingyang */ public int countRangeSum(int[] nums, int lowe ...

  6. [Swift]LeetCode327. 区间和的个数 | Count of Range Sum

    Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.Ra ...

  7. leetcode@ [327] Count of Range Sum (Binary Search)

    https://leetcode.com/problems/count-of-range-sum/ Given an integer array nums, return the number of ...

  8. 【LeetCode】327. Count of Range Sum

    题目: Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusiv ...

  9. leetcode327 Count of Range Sum

    问题描述: 给定一个整数数组nums,返回其所有落在[low, upper]范围内(包含边界)的区间和的数目. 区间和sums(i, j)的定义为所有下标为i到j之间(i ≤ j)的元素的和,包含边界 ...

随机推荐

  1. MVP社区巡讲-云端基础架构:12月5日北京站 12月12日上海站

    紧跟当今的技术发展趋势还远远不够,我们要引领变革!加入本地技术专家社区,获取真实案例.实况培训演示以及探讨新一代解决方案.在此活动中,您将: 了解如何运用开源(OSS)技术.Microsoft 技术及 ...

  2. Django admin美化插件suit应用[原创]

    前言 由于比较懒,自己弄了一个用户验证,没有自己写后台,用了django自带的user认证,并通过admin直接进行管理,但默认的admin并不漂亮,于是使用了这个django-suit插件,效果对比 ...

  3. 利用rebase来压缩多次提交

    我们可以用Git merge –squash来将分支中多次提交合并到master后,只保留一次提交历史.但是有些提交到github远程仓库中的commit信息如何合并呢? 历史记录 首先我们查看一下m ...

  4. 创建或打开解决方案时提示"DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x86"错误的解决方案

    提示"DotNetCore.1.0.1-SDK.1.0.0.Preview2-003131-x86"错误的解决方案: 1.检查是否有C:\Program Files (x86)\d ...

  5. fastjson-alibaba

    fastjson使用 package com.alibaba.json.demo; import org.junit.Assert; import com.alibaba.fastjson.JSON; ...

  6. [C1] C1FlexGrid 排除非绑定列的验证效果

    一.前言 前提是 C1FlexGrid 中存在数据绑定列和自定义列(非数据绑定列),此时如果该行编辑后出现排他错误,自定义列也会出现验证结果的红色边框: 但是自定义列如果只是一些按钮操作,提示说明什么 ...

  7. 【无私分享:ASP.NET CORE 项目实战(第十四章)】图形验证码的实现

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 很长时间没有来更新博客了,一是,最近有些忙,二是,Core也是一直在摸索中,其实已经完成了一个框架了,并且正在准备在生产环境中 ...

  8. 偷天换日:网络劫持,网页js被伪装替换。

    偷天换日 3月12号石家庄一个客户(后面简称乙方)有几家门店,平台收银(web)有一些功能无法正常使用,平台有上千家门店在使用,到目前为止别的省份都没有此问题.远程协助发现,js日期控件无法正常调用, ...

  9. 关于Linux下转换oracle字符集

    前阵子给以同事导oracle数据库,但是发现导入后数据都是乱码,下面是自己解决这个问题的一些小整理. 比如: #su oralce $export ORACLE_SID=orcl $export OR ...

  10. mysql awr 1.0.5 GA正式版发布

    1.0.5变更内容 1.修复centos 7下swap值不正确:2.中文乱码:3.begin/end snap下拉显示Mysql启动时间:4.两次快照间不能重启过:5.新增tab页面查看mysql存储 ...