Skip to content

Commit 9c4afb3

Browse files
committed
Update count-of-range-sum.py
1 parent 46bce45 commit 9c4afb3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Python/count-of-range-sum.py

+42
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,45 @@ def countAndMergeSort(sums, start, end, lower, upper):
5353
for i in xrange(len(nums)):
5454
sums[i + 1] = sums[i] + nums[i]
5555
return countAndMergeSort(sums, 0, len(sums), lower, upper)
56+
57+
58+
# Divide and Conquer solution.
59+
class Solution2(object):
60+
def countRangeSum(self, nums, lower, upper):
61+
"""
62+
:type nums: List[int]
63+
:type lower: int
64+
:type upper: int
65+
:rtype: int
66+
"""
67+
def countAndMergeSort(sums, start, end, lower, upper):
68+
if end - start <= 0: # The size of range [start, end] less than 2 is always with count 0.
69+
return 0
70+
71+
mid = start + (end - start) / 2
72+
count = countAndMergeSort(sums, start, mid, lower, upper) + \
73+
countAndMergeSort(sums, mid + 1, end, lower, upper);
74+
j, k, r = mid + 1, mid + 1, mid + 1
75+
tmp = []
76+
for i in xrange(start, mid + 1):
77+
# Count the number of range sums that lie in [lower, upper].
78+
while k <= end and sums[k] - sums[i] < lower:
79+
k += 1
80+
while j <= end and sums[j] - sums[i] <= upper:
81+
j += 1
82+
count += j - k
83+
84+
# Merge the two sorted arrays into tmp.
85+
while r <= end and sums[r] < sums[i]:
86+
tmp.append(sums[r])
87+
r += 1
88+
tmp.append(sums[i])
89+
90+
# Copy tmp back to sums
91+
sums[start:start+len(tmp)] = tmp
92+
return count
93+
94+
sums = [0] * (len(nums) + 1)
95+
for i in xrange(len(nums)):
96+
sums[i + 1] = sums[i] + nums[i]
97+
return countAndMergeSort(sums, 0, len(sums) - 1, lower, upper);

0 commit comments

Comments
 (0)