327. Count of Range Sum (Solution 1)

复制代码
package LeetCode_327

/**
 * 327. Count of Range Sum
 * https://leetcode.com/problems/count-of-range-sum/
 * Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.

Example 1:
Input: nums = [-2,5,-1], lower = -2, upper = 2
Output: 3
Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.

Example 2:
Input: nums = [0], lower = 0, upper = 0
Output: 1

Constraints:
1. 1 <= nums.length <= 105
2. -231 <= nums[i] <= 231 - 1
3. -105 <= lower <= upper <= 105
4. The answer is guaranteed to fit in a 32-bit integer.
 * */
class Solution {
    /**
     * solution 1: Accumulative array, then check sum of range if correct, TLE: 61/67 test cases passed; Time:O(n^2), Space:O(n)
     * solution 2: Merge sort, O(nlogn)
     * */
    fun countRangeSum(nums: IntArray, lower: Int, upper: Int): Int {
        var result = 0
        val size = nums.size
        val dp = LongArray(size)
        dp[0] = nums[0].toLong()
        for (i in 1 until size) {
            dp[i] = nums[i] + dp[i - 1]
        }
        for (i in 0 until size) {
            for (j in 0 until size) {
                if (i > j) {
                    //where i <= j
                    continue
                }
                val curSum = sumRange(dp, i, j)
                if (curSum in lower..upper) {
                    result++
                }
            }
        }
        return result
    }

    private fun sumRange(dp: LongArray, i: Int, j: Int): Long {
        val sum = if (i == 0) dp[j] else dp[j] - dp[i - 1]
        return sum
    }
}
复制代码

 

posted @   johnny_zhao  阅读(29)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-08-01 230. Kth Smallest Element in a BST
2020-08-01 1446. Consecutive Characters
2020-08-01 340. Longest Substring with At Most K Distinct Characters
2020-08-01 1004. Max Consecutive Ones III
2020-08-01 485. Max Consecutive Ones
点击右上角即可分享
微信分享提示