leetcode with python:303. Range Sum Query - Immutable

题目:

Given an integer array nums, handle multiple queries of the following type:

Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.

Implement the NumArray class:
NumArray(int[] nums) Initializes the object with the integer array nums.
int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).

在已知nums这个阵列值的情况下,设计一个函式
需要left跟right参数,回传nums里index範围在left~right里的值总和

这题我选择事先存好值加快sumRange函数的执行

class NumArray:    def __init__(self, nums: List[int]):        self.record=[]        x=0        for i in nums:            x=x+i            self.record.append(x)    def sumRange(self, left: int, right: int) -> int:        if left==0:            return self.record[right]        else:            return self.record[right]-self.record[left-1]

我们逐各个函数来解释:
(1)init:
透过nums建立一个record阵列
里面纪录至该index所有阵列元素相加的值
(2)sumRange:
当left是0时我们只需要回传record[right]即可(index 0~right的和)
而当left不是0时我们则要回传record[right]-record[left-1]
(index left~right的和=index 0~right的和 - index 0~left-1的和)
最后执行时间84ms(faster than 93.29%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章