ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Leetcode: 1508 Range Sum of Sorted Subarray Sums

2021-08-17 19:03:08  阅读:181  来源: 互联网

标签:right idx nums sum Sums range Range array Sum


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.

标签:right,idx,nums,sum,Sums,range,Range,array,Sum
来源: https://www.cnblogs.com/tmortred/p/15153719.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有