• 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
        }
    }
  • 相关阅读:
    ABAP 销售范围
    C语言深度剖析自测题8解析
    Ubutun13.10下安装fcitx
    各种Web服务器与Nginx的对比
    Hadoop2.2.0在Ubuntu编译失败解决方法
    网站上在给出邮箱地址时不直接使用@符号的原因
    IPython notebook在浏览器中显示不正常的问题及解决方法
    input只读效果
    阿里实习生电面题目:输出给定字符串的全部连续子串
    DNS 放大
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15086345.html
Copyright © 2020-2023  润新知