赞
踩
func subarraySum(nums []int, k int) int {
cnt := 0
n := len(nums)
for i := 0; i < n; i++ {
sum := 0
for j := i; j < n; j++ {
sum += nums[j]
if sum == k {
cnt++
}
}
}
return cnt
}
type NumArray struct { preSums []int } func Constructor(nums []int) NumArray { n := len(nums) sums := make([]int, n+1) sum := 0 for i := 0; i < n; i ++ { sum += nums[i] sums[i+1] = sum } return NumArray{sums} } func (this *NumArray) SumRange(left int, right int) int { return this.preSums[right+1] - this.preSums[left] }
type NumMatrix struct { nums [][]int } func Constructor(matrix [][]int) NumMatrix { m, n := len(matrix), len(matrix[0]) nums := make([][]int, m+1) for i := 0; i <= m; i++ { nums[i] = make([]int, n+1) } for i := 1; i <= m; i++ { for j := 1; j <=n; j++ { nums[i][j] =nums[i-1][j] + nums[i][j-1] - nums[i-1][j-1] + matrix[i-1][j-1] } } return NumMatrix{nums} } func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int { return this.nums[row2+1][col2+1] - this.nums[row1][col2+1] - this.nums[row2+1][col1] + this.nums[row1][col1] }
func pivotIndex(nums []int) int { var sum int n := len(nums) preSums := make([]int, n+1) // 计算前缀和 for i := 1; i <= n; i++ { sum += nums[i-1] preSums[i] = sum } for i := 0; i < n; i++ { if preSums[i] == preSums[n] - preSums[i+1] { return i } } return -1 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。