leetcode303.[DP] Range Sum Query - Immutable

来源:互联网 发布:淘宝极有家优质网店 编辑:程序博客网 时间:2024/05/16 08:19

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

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

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
一开始,没看到数组是不可变的,然后觉得这题和dp有虾米关系,然后就TLE了(真的是图样图森破啊)

class NumArray(object):    def __init__(self, nums):        self.Nums=[0]        for i in range(len(nums)):            self.Nums.append(self.Nums[i]+nums[i])    def sumRange(self, i, j):        return self.Nums[j+1]-self.Nums[i]
0 0
原创粉丝点击