LeetCode 327. Count of Range Sum(TreeMap)

这是一篇关于LeetCode 327题目的博客,主要讨论如何利用Java和TreeMap数据结构解决在给定数组中寻找满足特定范围条件的子数组和的问题。通过将子数组和转化为前缀和的差值,借助TreeMap以O(nlogn)的时间复杂度找出符合条件的子数组个数。

Count of Range Sum

Hard

Given an integer array nums, 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 (ij), inclusive.

Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.

Example:

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

题意

给定一个数组nums和整数区间[lower, upper],求nums的连续子串的个数,使得连续子串的和在区间[lower, upper]内。

思路

将连续子串和转化为两个前缀和相减,即在n个前缀和中寻找(i, j)对,使得lower <= sum[i] - sum[j] <= upper && i > j. 用TreeMap保存之前已经遍历过的前缀和,Tr

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值