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.
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.
O(N^2)解法
最直接的想法当然就是遍历求和了。但是这样是无法通过测试的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution3(object): defcountRangeSum(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: int """
sums = []
for i inrange(len(nums)): s = 0 for j inrange(i, len(nums)): s += nums[j] if lower <= s <= upper: sums.append(s) returnlen(sums)
死亡凝视
必须要想出复杂度是Nlog(N)的算法才行。但是问题也很明显,
要想找出所有的s(i,j) for 0 <= i <= j < n and lower <= s(i,j) <= upper
那必须要进行遍历啊,因此时间复杂度必须是N^2。
啊啊,实在想不出来了。
第二天,既然要求时间复杂度为NlogN那么就必然不能遍历求出s(i,j),但是
题目要求的是求出Num(s(i,j)) for 0 <= i <= j < n and lower <= s(i,j) <= upper
,也就是说给出个数就行,因此确实不一定要给出所有的s(i,j)。嗯,有点进展了。