[leetcode] 327. Count of Range Sum 解题报告
来源:互联网 发布:零基础学java pdf 编辑:程序博客网 时间:2024/06/14 00:33
题目链接: https://leetcode.com/problems/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:
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
.
思路: 因为是要计算区间, 因此我们可以将其前n个元素求和放到一个数组中, 这样当我们我计算区间[i, j]的和时, 只要用sum[j+1] - sum[i]即可, 这样就可以在O(1)的时间取得任意区间的和.
现在问题是求有多少个区间的和大小落在[lower, upper]之间, 一个native的算法就是枚举各个区间, 这种的时间复杂度很明显是O(n^2).
一个更好的方法是利用分治法来处理. 即利用归并排序算法的将数组分成左右两边, 在合并左右数组的时候对于左边数组中的每一个元素在右边数组找到一个范围, 使得在这个范围中的的元素与左边的元素构成的区间和落在[lower, upper]之间. 即在右边数组找到两个边界, 设为m, n, 其中m是在右边数组中第一个使得sum[m] - sum[i] >= lower的位置, n是第一个使得sum[n] - sum[i] > upper的位置, 这样n-m就是与左边元素i所构成的位于[lower, upper]范围的区间个数. 因为左右两边都是已经有序的, 这样可以避免不必要的比较.
其时间复杂度为O(n log n)
代码如下:
class Solution {public: int mergeSort(vector<long>& sum, int lower, int upper, int low, int high) { if(high-low <= 1) return 0; int mid = (low+high)/2, m = mid, n = mid, count =0; count = mergeSort(sum,lower,upper,low,mid) + mergeSort(sum,lower,upper,mid,high); for(int i =low; i< mid; i++) { while(m < high && sum[m] - sum[i] < lower) m++; while(n < high && sum[n] - sum[i] <= upper) n++; count += n - m; } inplace_merge(sum.begin()+low, sum.begin()+mid, sum.begin()+high); return count; } int countRangeSum(vector<int>& nums, int lower, int upper) { int len = nums.size(); vector<long> sum(len + 1, 0); for(int i =0; i< len; i++) sum[i+1] = sum[i]+nums[i]; return mergeSort(sum, lower, upper, 0, len+1); }};参考: http://huntzhan.org/leetcode-count-of-range-sum/
https://leetcode.com/discuss/79083/share-my-solution
- [leetcode] 327. Count of Range Sum 解题报告
- [Leetcode] 327. Count of Range Sum 解题报告
- <LeetCode OJ> 327. Count of Range Sum
- leetcode 327. Count of Range Sum
- Leetcode 327. Count of Range Sum[hard]
- LeetCode 327. Count of Range Sum
- leetcode 327.Count of Range Sum
- LeetCode 327. Count of Range Sum
- LeetCode 327. Count of Range Sum
- leetcode 327. Count of Range Sum
- [leetcode]327. Count of Range Sum
- leetcode 327. Count of Range Sum
- leetcode Count of Range Sum
- LeetCode Count of Range Sum
- [LeetCode]Count of Range Sum
- Leetcode Count of Range Sum
- leetcode Count of Range Sum
- []LeetCode]Count of Range Sum
- 二进制分流法
- linux shell 中判断字符串为空的正确方法
- C&C++编译过程
- Android学习基础之onSaveInstanceState和onRestoreInstanceState触发的时机
- OC关联objc_setAssociatedObject
- [leetcode] 327. Count of Range Sum 解题报告
- 自己写的java邮件客户端
- 第8周项目3 - 指向学生类的指针
- javasript dom 中获取元素类名 或者 改变类 引用另外一个类
- 决策树介绍一
- java杂记
- oracle导出、导入dmp文件
- UVA4260Fortune Card Game【dp】
- 第10、11周-程序阅读补充(1)