303. Range Sum Query - Immutable [easy] (Python)

深入解析MSPM0系列Keil开发中‘ti_msp_dl_config.h‘缺失问题的根源与修复 本文深入解析TI MSPM0系列Keil开发中'ti_msp_dl_config.h'文件缺失问题的根源与修复方法。该错误常见于编译时提示file not found,主要因SysConfig工具未正确生成或工程路径配置错误导致。文章提供了从环境检查、手动生成文件到工程配置调整的系统化解决方案,帮助开发者快速解决这一常见KEIL开发难题。 阅读详情

题目链接

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

题目原文

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.

题目翻译

给定一个整数数组nums,求其下标i到j(i≤j,包括i和j)之间的所有元素的和。
比如,给定 nums = [-2, 0, 3, -5, 2, -1]:
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
注意:假设数组不会变化;sumRange函数会被调用非常多次。

思路方法

题目说明了该函数会被调用多次,所以应该对此作出优化。题目给了执行的例子:

# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
# numArray.sumRange(0, 1)
# numArray.sumRange(1, 2)

经测试,每次调用sumRange都重新计算结果会导致超时。

思路一

在初始化的时候,将从第一个元素开始到当前位置的所有元素的和求出来,存放到数组sums中。那么每次求一个范围的和时,只要计算两个下标处和的差即可。

代码

class NumArray(object):
    def __init__(self, nums):
        """
        initialize your data structure here.
        :type nums: List[int]
        """
        self.sums = [0] * (len(nums)+1)
        for i in xrange(len(nums)):
            self.sums[i+1] = self.sums[i] + nums[i]

    def sumRange(self, i, j):
        """
        sum of elements nums[i..j], inclusive.
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.sums[j+1] - self.sums[i]

思路二

求部分和的要求正好与树状数组(Binary Index Tree,BIT)的操作吻合,所以可以实现一个BIT来做这道题。不过,实际上题目说了数组不会变化,所以BIT的优势并没有完全发挥,BIT的更新和计算部分和的时间复杂度都是O(logn)。

代码

class NumArray(object):
    def __init__(self, nums):
        """
        initialize your data structure here.
        :type nums: List[int]
        """
        self.length = len(nums)
        self.BIT = [0] * (self.length + 1)
        for i in xrange(len(nums)):
            self.updateBIT(i, nums[i])

    def updateBIT(self, i, val):
        i += 1
        while i <= self.length:
            self.BIT[i] += val
            i += i & (-i)

    def getBITsum(self, i):
        i += 1
        res = 0
        while i > 0:
            res += self.BIT[i]
            i -= i & (-i)
        return res

    def sumRange(self, i, j):
        """
        sum of elements nums[i..j], inclusive.
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.getBITsum(j) - self.getBITsum(i-1)

思路三

这题还可以用线段树(SegmentTree)来解决,每次查询的复杂度也是O(logn)。

代码

class NumArray(object):
    def __init__(self, nums):
        """
        initialize your data structure here.
        :type nums: List[int]
        """
        self.ST = SegmentTree(nums)

    def sumRange(self, i, j):
        """
        sum of elements nums[i..j], inclusive.
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.ST.query(self.ST.root, i, j)

class Node(object):
    def __init__(self, start, end):
        self.left, self.right = None, None
        self.start, self.end, self.sum = start, end, 0

class SegmentTree(object):
    def __init__(self, vals):
        self.root = self.build(0, len(vals)-1, vals)

    def build(self, start, end, vals):
        if start > end:
            return None
        root = Node(start, end)
        if start != end:
            mid = start + (end - start) / 2
            root.left = self.build(start, mid, vals)
            root.right = self.build(mid+1, end, vals)
            root.sum = root.left.sum + root.right.sum
        else:
            root.sum = vals[start]
        return root

    def query(self, root, start, end):
        if not root or start > end:
            return 0
        if start <= root.start and end >= root.end:
            return root.sum
        mid = root.start + (root.end - root.start) / 2
        left_sum = right_sum = 0
        if start <= mid:
            if end > mid:
                left_sum = self.query(root.left, start, mid)
            else:
                left_sum = self.query(root.left, start, end)
        if end > mid:
            if start <= mid:
                right_sum = self.query(root.right, mid+1, end)
            else:
                right_sum = self.query(root.right, start, end)
        return left_sum + right_sum

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51720978

CST微波工作室端口设置保姆级教程:从波导端口到离散端口,手把手教你搞定S参数仿真 本文提供CST微波工作室端口设置的详细教程,涵盖波导端口和离散端口的选择与配置,助力工程师精准完成S参数仿真。通过微带线滤波器案例,详解端口尺寸、阻抗设置及常见问题排查,提升仿真效率与准确性。 阅读详情

相关推荐

candence layout快捷键

摁住鼠标左键再框选:选中 摁住鼠标右键再框选:放大 选中之后,滚动鼠标滚轮进行放大缩小。 F:回到全局 shift+V:缩小 键盘的箭头:移动视图 F1:显示帮助文档Candence help F2:保存 点击r,画出矩形时不双击鼠标,点击F3,可以设置尺寸。 Creat-Shape-Path Creat-Wiring-Bus:画多根线。F3设置线宽、间距等。 选中金属后,Shift+G画保护环guard ring。F3可以设置距离金属的间距、保护环的形状。 Path和Rectang

weixin_45861827的博客 2655

sum,range

时间一长,东西就爱忘记,也是因为自己不扎实的缘故吧。再记一下sum和range的使用。 sum是Python中一个很实用的函数,sum()的参数是一个列表形式。 例如:sum(1,2,3) 就会出错,而sum([1,2,3]) 就会出现结果为6 大家都知道range这个很强大,很方便的函数 例如: range(1,12) #代表从1到12(不包括12)range(1,12,2) #代

ccy950903的博客 5322

Python离线断网情况下安装numpy、pandas和matplotlib等常用第三方包

联网情况下在命令终端CMD中输入“pip install numpy”即可自动安装,pandas和matplotlib同理一样方法进行自动安装。 工作的电脑不能上外网,所以不能通过直接输入pip命令来安装。 环境:电脑上已经安装了Python(没有安装的请参考其他教程)。 Python离线断网情况下安装numpy、pandas和matplotlib等常用第三方包的步骤如下: ...

dayou7738的博客 4942

Range Sum Query - Immutable

Given an integer arraynums, find the sum of the elements between indicesiandj(i≤j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) ->...

dianxiangong2403的博客 120

阿里云网络架构设计

背景 一个企业上云,首先要考虑整个网络的规划,涉及到云上和云下的网络规划,云上VPC的规划,云上不同地域VPC的互通,云上可用区的选择等等,所以一定要提前规划好整体的网络架构,现在阿里云云上的虚拟化网络解决方案已经完全转向 了云企业网,所以所有使用阿里云的企业客户多多少少都会使用阿里云的CEN 支撑自己的业务。 云企业网介绍 云企业网(Cloud Enterprise Network)是承载在阿里云提供的高性能、低延迟的私有全球网络上的一张高可用网络。 IDC专线接入CEN 首先面临的是云上和云下打通,那么

修电脑的码农 4838

保姆级教程:用Labelme标注车辆关键点,并一键转成YOLOv8-pose训练格式

本文提供了一份详细的车辆底盘关键点标注教程,从使用Labelme进行标注到一键转换为YOLOv8-pose训练格式的全流程指南。特别针对工业检测和自动驾驶场景,分享了标注规范、格式转换脚本及常见问题解决方案,帮助开发者高效准备训练数据并优化模型性能。

weixin_27419879的博客 307

excel的SUMIF和SUMIFS函数的区别和联系

目录 1.SUMIF函数 2.SUMIFS 3.SUMIF和SUMIFS函数的异同 1.SUMIF函数 (1)语法:SUMIF(range,criteria,[sum_range]) 即SUMIF(条件范围,条件,[求和范围]) 参数:range:必要项,表示条件范围,用于条件判断的单元格区域;    criteria:必要项,表示条件,由数字、逻辑表达式等组成的判定条件,例如,16、"16"、">16"、"女生"或">"&A1。;    sum_rang...

weixin_50853979的博客 1万+

国产谷歌地球,地形分析秒杀同款地图软件

咱们做地质、林业、水文、水利、电力、GIS、地图、水保、环境的,需要经常用到各种数据,比如影像、地形、矢量、模型等,但目前80%的规划大数据展示都离不开ArcGIS,令人头大的是很多朋友连ArcGIS软件安装起来都费劲。。。 那不会ArcGIS又装不了Google Earth怎么开展工作? 今天推荐大家一款国产免费专业地图浏览下载测量分析神器—图新地球 图新地球,国产三维gis软件。可以查看高清卫星影像地形以及其他很多常用电子地图,对地图需求的掌握远胜过Google Maps,而且上手比国外软件要简单

GISWorld3D的博客 3685

303. Range Sum Query - Immutable

303. Range Sum Query - Immutable 1. 题目 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...

凌凌小博客 182

IAR for ARM 搭建STM32F103C8T6工程模板(实战指南)

本文详细介绍了如何在IAR for ARM开发环境中为STM32F103C8T6微控制器搭建完整的工程模板。从环境准备、固件库获取、目录结构设计到工程配置与编译调试,提供了实战指南和常见问题解决方案,帮助开发者快速建立稳定的STM32开发环境。

fun88的博客 988

World Creator地形导入UE

导出预设选择高度图(heigh map)格式选择PNG 16位,或者RAW 16位,需要反转y轴(与虚幻不同),命名格式会自动带一个× , 将×改成_ 或者删掉自己命名 (虚幻名称不支持x符号)导入虚幻 , 修改Z轴 , 就是用 地形最高 - 地形最低 , 然后除以512 , 再乘以100。把这个数字填入Z轴缩放 , 点击生成即可。

UE星空 2154

leetcode 303. Range Sum Query - Immutable 【easy】

题目: 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) ->

this->ou 474

ros2 gazebo仿真阿克曼小车搭载livox mid360雷达流程

流程简介:仿真环境的搭建需要安装ROS2和Gazebo。使用的是Humble版本,需要确认是否已经正确安装。然后是阿克曼小车模型的URDF,需要包括底盘、转向机构、驱动轮等,需要参考现有的阿克曼模型,比如ClearPath的Husky,但需要调整参数。Livox Mid360雷达在Gazebo中的仿真可能没有现成的插件,需要使用通用3D LiDAR插件来模拟。IMU的仿真相对简单,但需要注意噪声模型,以接近真实数据。

weixin_43802726的博客 3211

leetcode 303: Range Sum Query - Immutable

Range Sum Query - Immutable Total Accepted: 696 Total Submissions: 2406 Difficulty: Easy Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), i

西施豆腐渣 5684

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

LeetCode算法题-Range Sum Query Immutable(Java实现)

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33711647的博客 82

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

工作中使用到的单词(软件开发)

1.エイリアス   alias 别名 powershell使用 get-help 命令时,会得到与此命令 相关(别名)的命令 2.プロキシ proxy 代 理 3.プロモート   promote 促进,提升   开发的系统新功能上线发布,有时会使用到这个词,比如 STプロモート 还有使用リリース这个词的。比如STリリース。个人认为两者含义相同。 4.見逃し み................................................................

sun0322 6万+

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Leetcode 303 Range Sum Query - Immutable Python题解

题目大意输入一个数组,给定两个数组的索引i和j(i <= j),计算从索引i到j的和。 原题链接:303. Range Sum Query - Immutable题解一开始的时候我打算在初始化的时候用一个二维数组存储所有结果值,然后每次获取和的时候直接访问缓存的二维数组即可。 理想很美好,现实很扑街,惨遭MLE。class NumArray(object): def __init__(se

日复一日,年复一年 1004

LeetCode(303)Range Sum Query - Immutable

题目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)

指尖飞舞 5198

【LeetCode】303. Range Sum Query - Immutable 解题报告(Python)

【LeetCode】303. Range Sum Query - Immutable 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/range-sum-query-immutable/description/ 题目描述: Given an integer array nums, find the sum of

负雪明烛 1835

303. Range Sum Query - Immutable(python+cpp)

题目: 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) -&gt; 1 sumRange(2, 5) -&gt; -1 ...

小湉湉的博客 286

LeetCode 303:Range Sum Query - Immutable (python)

题目描述 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 示例如下: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumR...

tzjzrq的专栏 245

python编程语言汇总-编程语言学习:python有趣用法汇总

用python过程中经常会不经意间遇到非常有趣的用法,于是特意搜集了一些。有趣的用法1.for-else用法循环正常结束则执行else语句。一般用于循环找符合条件的元素,如果找到则break调出循环,不会触发else;如果没有找到(完整运行循环)则print not found《Effictive Python》一书中对for-else用法提出了质疑,主要观点是可以通过封装成函数来取代这一用法,而...

weixin_37988176的博客 257

区域和检索 - 数组不可变

区域和检索 - 数组不可变 题目: 给定一个整数数组 nums,处理以下类型的多个查询: 计算索引 left 和 right (包含 left 和 right)之间的 nums 元素的 和 ,其中 left <= right 实现 NumArray 类: NumArray(int[] nums) 使用数组 nums 初始化对象 int sumRange(int i, int j) 返回数组 nums 中索引 left 和 right 之间的元素的 总和 ,包含 left 和 right 两点(也

KobeSacre的博客 828

303. Range Sum Query - Immutable(和累加法)

题目 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) -&gt; 1 sumRange(2, 5) -&gt; -1 ...

xunalove的博客 422

第二章 java流程控制

一.条件判断 if(条件判断){ A } if(条件判断){ A } else { B } if(条件判断){ A } else if(条件判断){ B }… else{ C } 多分支判断,最多只执行一个分支; 从上向下进行分支判断,如果某个判断成立,执行其中的代码块,并且终止后面所有的判断 某个分支判断执行,说明它之前的所有的判断都不成立。 二.循环 while (条件判断) { 循环体 ...

Forget_the_past的博客 344

LeetCode:303. Range Sum Query - Immutable - Python

问题描述: 303. Range Sum Query - Immutable 给定一个整数数组 nums,求出数组从索引 i到j (i ≤ j)范围内元素的总和,包含i, j 两点。 示例: 给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange() sumRange(0, 2) -&amp;amp;gt; 1 sumRange(2, 5) -...

Growth Diary 649
上一篇: 28. Implement strStr() [easy] (Python)
下一篇: 371. Sum of Two Integers [easy] (Python)
coder_orz
博客等级 码龄14年 102粉丝 90原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值