1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| func countRangeSum(nums []int, lower int, upper int) int { preSum := make([]int, len(nums) + 1) for i, v := range nums { preSum[i + 1] = preSum[i] + v }
var countSum func([]int) int
countSum = func(arr []int) int { length := len(arr) if length <= 1 { return 0 }
left := append([]int{}, arr[:length/2]...) right := append([]int{}, arr[length/2:]...)
count := countSum(left) + countSum(right)
l, r := 0, 0 for _, v := range left { for l < len(right) && right[l] - v < lower { l++ }
for r < len(right) && right[r] - v <= upper { r++ }
count += r - l }
p1, p2 := 0, 0 for i := range arr { if p1 < len(left) && ( p2 == len(right) || left[p1] <= right[p2]) { arr[i] = left[p1] p1++ } else { arr[i] = right[p2] p2++ } }
return count }
return countSum(preSum) }
|