1. 程式人生 > >Leetcode 327.區間和的個數

Leetcode 327.區間和的個數

區間和的個數

給定一個整數陣列 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。

 

使用TreeMap來儲存每個字首和的計數

 1 import java.util.TreeMap;
 2 
 3 public class Solution {
 4 
 5     public static void main(String[] args){
 6         int[] nums={-2,5,-1};
 7         System.out.println(countRangeSum(nums,-2,2));
8 } 9 10 public static int countRangeSum(int[] nums, int lower, int upper) { 11 if (nums == null || nums.length == 0) return 0; 12 long[] sums = new long[nums.length]; 13 sums[0] = nums[0]; 14 for (int i = 1; i < nums.length; i++) sums[i] = sums[i - 1] + nums[i];
15 int total = 0; 16 TreeMap<Long, Integer> treemap = new TreeMap<>(); 17 for (int i = 0; i < nums.length; i++) { 18 if (lower <= sums[i] && sums[i] <= upper) { 19 total++; 20 } 21 for (Integer count : treemap.subMap(sums[i] - upper, true, sums[i] - lower, true).values()) { 22 total += count; 23 } 24 Integer count = treemap.get(sums[i]); 25 if (count == null) { 26 count = 1; 27 } 28 else { 29 count++; 30 } 31 treemap.put(sums[i], count); 32 } 33 return total; 34 } 35 }