Leetcode 简单三十五 303.区域和检索 - 数组不可变 - Go语言中文社区

Leetcode 简单三十五 303.区域和检索 - 数组不可变


区域和检索-数组不可变

动态规划:

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);
 */

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_36688622/article/details/96194557
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-25 16:31:04
  • 阅读 ( 1459 )
  • 分类:算法

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢