子数组和排序后的区间和(Range Sum of Sorted Subarray Sums)
LeetCode传送门 1508. 子数组和排序后的区间和
题目
给你一个数组 nums ,它包含 n 个正整数。你需要计算所有非空连续子数组的和,并将它们按升序排序,得到一个新的包含 n * (n + 1) / 2 个数字的数组。
请你返回在新数组中下标为 left 到 right (下标从 1 开始)的所有数字和(包括左右端点)。由于答案可能很大,请你将它对 10^9 + 7 取模后返回。
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 10^9 + 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.
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4
Output: 6
Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10
Output: 50
Constraints:
- n == nums.length
- 1 <= nums.length <= 1000
- 1 <= nums[i] <= 100
- 1 <= left <= right <= n * (n + 1) / 2
思考线
解题思路
首先根据题意
-
我们需要把排列后的数组计算出来,在这里我们需要用到两层
for循环。 -
然后我们对结果数组进行排序。
-
然后对数组中的第
left -1到right -1位进行相加操作。
function rangeSum(nums: number[], n: number, left: number, right: number): number {
const resArr = [];
const len = nums.length;
const MOD = 1000000007
for (let i = 0; i < len; i++) {
resArr.push(nums[i]);
let calculate = nums[i];
for (let j = i + 1; j < len; j++) {
calculate += nums[j];
resArr.push(calculate);
}
}
console.log(resArr.sort((a,b) => a -b))
return resArr.sort((a,b) => a -b).slice(left - 1, right).reduce((res, cur) => res = (cur + res) % MOD, 0)
};
时间复杂度分析
我们计算结果数组用的时间复杂度为O(n^2)
由于排序的结果数组的长度为 n(n+1)/2, 所以sort排序的时间复杂度为O(logn)
最后计算的长度我们假设为k = right -right,所以总体时间复杂度为O(n^2*log(n) + K)
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。