給定一個整數數組 nums,返回區間和在 [lower, upper] 之間的個數,包含 lower 和 upper。
區間和 S(i, j) 表示在 nums 中,位置從 i 到 j 的元素之和,包含 i 和 j (i ≤ j)。
說明:
最直觀的算法復雜度是 O(n2) ,請在此基礎上優化你的算法。
示例:
輸入: nums = [-2,5,-1], lower = -2, upper = 2,
輸出: 3
解釋: 3個區間分別是: [0,0], [2,2], [0,2],它們表示的和分別為: -2, -1, 2。
代碼
class Solution {public int countRangeSum(int[] nums, int lower, int upper) {TreeMap<Long,Integer> tree=new TreeMap<>();tree.put(0L,1);long sum=0;int count=0;for(int i:nums){sum+=i;for(int num:tree.subMap(sum-upper,true,sum-lower,true).values())
//滿足條件區間和的個數count+=num;tree.put(sum,tree.getOrDefault(sum,0)+1);}return count;}
}