社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
区域和检索-数组不可变
动态规划:
PHP,80ms
class NumArray {
/**
* @param Integer[] $nums
*/
private $sum = [];
function __construct($nums) {
$this->$sum[0] = 0;
for($i = 1;$i <= count($nums);$i++){
$this->$sum[$i] = $this->$sum[$i-1] + $nums[$i-1];
}
}
/**
* @param Integer $i
* @param Integer $j
* @return Integer
*/
function sumRange($i, $j) {
return $this->$sum[$j+1] - $this->$sum[$i];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* $obj = NumArray($nums);
* $ret_1 = $obj->sumRange($i, $j);
*/
golang,50ms
type NumArray struct {
Sum []int
}
func Constructor(nums []int) NumArray {
var SumNum NumArray
SumNum.Sum = append(SumNum.Sum,0)
for i := 1;i <= len(nums);i++ {
SumNum.Sum = append(SumNum.Sum,SumNum.Sum[i-1]+nums[i-1])
}
return SumNum
}
func (this *NumArray) SumRange(i int, j int) int {
return this.Sum[j+1] - this.Sum[i]
}
/**
* Your NumArray object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.SumRange(i,j);
*/
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!