zoukankan      html  css  js  c++  java
  • Leetcode: 1508 Range Sum of Sorted Subarray Sums

    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.
    
  • 相关阅读:
    图像全參考客观评价算法比較
    单片机project师必备的知识
    ACM-并查集之小希的迷宫——hdu1272
    ArcGIS教程:加权总和
    九度 题目1368:二叉树中和为某一值的路径
    解决solr搜索多词匹配度和排序方案
    具体解释linux文件处理的的经常使用命令
    Hotel
    Unity3D 射线指定层获取GameObject 注意 LayerMask
    ios设计一部WindowsPhone手机
  • 原文地址:https://www.cnblogs.com/tmortred/p/15153719.html
Copyright © 2011-2022 走看看