Leetcode - Range Addition
Leetcode - Range Sum Query 2D - Immutable

Leetcode - Range Sum Query - Immutable

violet posted @ May 09, 2020 02:11:48 AM in 算法 with tags Algorithm Golang array , 206 阅读

https://leetcode.com/problems/range-sum-query-immutable/

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

 

type NumArray struct {
    sum []int
}


func Constructor(nums []int) NumArray {
    if len(nums) == 0 {
        return NumArray{}
    }
    sum := make([]int, len(nums))
    sum[0] = nums[0]
    for i := 1; i < len(nums); i++ {
        sum[i] = sum[i-1] + nums[i]
    }
    return NumArray{
        sum: sum,
    }
}


func (this *NumArray) SumRange(i int, j int) int {
    if i == 0 {
        return this.sum[j]
    }
    return this.sum[j] - this.sum[i-1]
}


/**
 * Your NumArray object will be instantiated and called as such:
 * obj := Constructor(nums);
 * param_1 := obj.SumRange(i,j);
 */

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter