Leetcode: 1508 Range Sum of Sorted Subarray Sums
阿新 • • 發佈:2021-08-17
Description
You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers. Return the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.
Example
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5 Output: 13 Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
分析
- 正確的思路
1. 採用二分 以 n=4, nums = [1,2,3,4] 為例, prefixSum = [1, 3, 6, 10] step1 猜一個數 M for i in range(4): 二分查找出 prefixSum 小於等於 M + nums[i] - nums[0] 個數 step2 如小於等於 M 的個數大於 rightnum 或 leftnum, 則縮小 M 的值 。 否則增大 M 值 (常規的 二分更新法則) 如小小於等於 M 的個數等於 rightnum 或者。leftnum。則進入到第三步 step3 total = 0 for i in range(4): curTotal = 0 for j in range(i, 4): curTotal += nums[j] if curTotal > M: break total += curTotal 2. 採用最小堆, 程式碼如下 import heapq class Solution(object): def rangeSum(self, nums, n, left, right): """ :type nums: List[int] :type n: int :type left: int :type right: int :rtype: int """ q, total_sum = [], 0 for i in range(n): heapq.heappush(q, [nums[i], i]) for i in range(1, right+1): v, idx = heapq.heappop(q) if i >= left: total_sum += v if n-1 > idx: idx += 1 heapq.heappush(q, [v+nums[idx], idx]) return total_sum % 1000000007
總結
Runtime: 560 ms, faster than 48.15% of Python online submissions for Range Sum of Sorted Subarray Sums.
Memory Usage: 29.2 MB, less than 88.89% of Python online submissions for Range Sum of Sorted Subarray Sums.