LeetCode: 303. Range Sum Query - Immutable

2020计算机专业保研夏令营面经:中科院计算所网数机试题目 计算所网络数据科学与技术重点实验室的第一阶段是机试。机试不限程序语言,要求提交源代码。 阅读详情

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) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

解题思路 —— 前缀和

记录下前缀和, 即,PrefixSum[i] 表示前 i 个数字的和。

特别地,当 i = 0 时, PrefixSum[i] = 0。

则 sumRange(i, j) = PrefixSum[j] - PrefixSum[i].

AC 代码

type NumArray struct {
    PrefixSum []int // 前缀和
}


func Constructor(nums []int) NumArray {
    arr := NumArray{ []int{0} }
    
    for i := 0; i < len(nums); i++{
        arr.PrefixSum = append(arr.PrefixSum, nums[i] + arr.PrefixSum[i])
    }
    
    return arr
}


func (this *NumArray) SumRange(i int, j int) int {
    return this.PrefixSum[j+1] - this.PrefixSum[i]
}


/**
 * Your NumArray object will be instantiated and called as such:
 * obj := Constructor(nums);
 * param_1 := obj.SumRange(i,j);
 */
Python爬虫实战:使用最新技术爬取新浪新闻首页数据 本文详细介绍了三种爬取新浪新闻首页的技术方案,从简单的requests-html到强大的Playwright,再到分布式Scrapy架构。小规模爬取:requests-html或aiohttp方案需要JavaScript渲染:Playwright方案大规模分布式爬取:Scrapy-Redis方案。 阅读详情

相关推荐

MUSIC算法翻车?Toeplitz矩阵重构如何解决DOA估计中的相干信源难题

本文深入探讨了MUSIC算法在相干信源DOA估计中失效的根本原因,并详细介绍了基于Toeplitz矩阵重构的协方差矩阵修复技术。该方法通过凸优化恢复协方差矩阵的理想结构,有效解决了信号子空间秩亏损问题,从而显著提升了MUSIC算法在相干和多径场景下的分辨精度与稳健性。

a2b3c4d5e的博客 255

区域和检索 - 数组不可变

区域和检索 - 数组不可变 题目: 给定一个整数数组 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的博客 833

易语言游戏Call调用避坑指南:主线程绑定与反检测实战

本文详细解析了易语言游戏Call调用中的主线程绑定与反检测技术,帮助开发者避免游戏崩溃和断线问题。通过分析线程检测原理、提供易语言实现方案及高级反检测技巧,如动态线程绑定和上下文伪装,确保Call调用的稳定性和安全性。文章还包含常见问题排查和性能优化建议,适用于游戏辅助开发领域。

weixin_29323365的博客 465

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

开源网格划分软件-Gmsh二次开发教程 (4)网格生成与控制​

​本章将深入讲解Gmsh的网格生成技术,包括全局/局部网格控制、边界层生成、自适应细化等,并提供完整的代码示例。

ZQGG的博客 1483

Yolov5s可视化网络结构图

Yolov5共有四种网络结构,每种网络深度和宽度上都不相同。 (1) Yolov5s可视化网络结构图:点击查看 (2) Yolov5m可视化网络结构图:点击查看 (3) Yolov5l可视化网络结构图:点击查看 (4) Yolov5x可视化网络结构图:点击查看 ...

江南研习社 15万+

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

题目链接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 = [-

Coder_Orz的博客 3204

从零部署奥比中光Gemini335L:Python SDK编译与手眼标定环境实战

本文提供了一份从零部署奥比中光Gemini 335L深度相机的完整实战指南。详细介绍了驱动安装、Python SDK编译、CMake配置及虚拟环境搭建等关键步骤,并重点解析了如何通过编译生成Python模块,最终实现深度图与点云数据获取,为后续的机械臂手眼标定工作奠定坚实基础。

weixin_29031161的博客 404

[LeetCode]303. Range Sum Query - Immutable

[LeetCode]303. Range Sum Query - Immutable题目描述思路开始的思路:存数组,将对应的区间内的数字相加 优化: 对于每一位,存入的是从第0位到当前位的和 返回的时候返回 [j] - [i - 1]即可代码开始的思路class NumArray { public: vector<int> nums; NumArray(vector<int>

Lcharon的博客 377

雷达气象学(8)——反射率因子图实战(强对流预警篇)

本文聚焦雷达反射率因子图在强对流预警中的实战应用,深入解析了柱状回波、有界弱回波区(BWER)、三体散射(TBSS)等关键回波结构特征,这些是识别超级单体风暴和大冰雹的核心“身份证”。文章强调从静态识别转向动态追踪与多源数据综合研判的思维转变,并提供了系统的实战分析流程与常见误区避坑指南,旨在提升对强对流天气的短临预警能力。

weixin_29213827的博客 494

基于潜在空间分数匹配的混合型表格数据合成方法

然而,在我们的模型中,β 预计会更小,因为我们不需要嵌入的分布精确地遵循标准高斯分布,因为我们还有一个额外的扩散模型。受 Transformer 在表格数据分类/回归任务中取得成功的启发,我们首先为每一列学习一个独特的标记器,然后将标记(列)级表示输入到 Transformer 中,以捕捉列之间错综复杂的关系。在第 4 节中,我们证明了通过这种设计,TABSYN 可以在不到 20 次函数评估(NFE)的情况下生成高质量的合成表格数据,这比其他基于扩散的表格数据合成方法要少得多。是标记器的可学习参数。

步子哥的博客 862

LeetCode //C - 303. Range Sum Query - Immutable

【代码】LeetCode //C - 303. Range Sum Query - Immutable。

Made in Code 1128

基于STM32+Lora设计的粮仓环境监测系统_PCB_416

为解决传统粮仓管理中存在的监测手段落后、数据实时性差、管理效率低下等问题,本项目设计并实现了一套基于STM32和LoRa技术的智能化粮仓环境监测系统。该系统由多个分布式传感器节点和一个中心网关组成,均采用STM32F103C8T6作为主控芯片。节点负责实时采集粮仓内的温度、湿度(SHT30)、粮食水分、二氧化碳及烟雾等多项环境参数,并通过LoRa无线网络将数据发送至网关。网关对数据进行汇聚后,利用Air780e 4G模块以MQTT协议将数据上传至华为云IoT平台。系统支持自动与手动两种控制模式,可根据环境阈

87

[leetcode]303. Range Sum Query - Immutable

[leetcode]303. Range Sum Query - Immutable Analysis 周五啦,端午小长假要开始啦~—— [嘻嘻~] Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 题目意思比较简单,就是给...

weixin_32135877的博客 139

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Leetcode 303. Range Sum Query - Immutable (Easy) (cpp)

Leetcode 303. Range Sum Query - Immutable (Easy) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 569

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

leetcode 303. Range Sum Query - Immutable

/* 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,

编码之路 274

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode--303. Range Sum Query - Immutable

问题链接:https://leetcode.com/problems/range-sum-query-immutable/ 这个问题属于数据结构设计的问题,属于开放式问题。 思路一:在查询时直接暴力计算,代码省略。 思路二:哈希缓存,初始化复杂度O(n^2),查询复杂度O(1),代码如下: private Map&lt;Pair&lt;Integer, Integer&gt;, Inte...

To_be_thinking的博客 315

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

西施豆腐渣 5687

LeetCode303——Range Sum Query - Immutable

LeetCode303——Range Sum Query - Immutable 插播一条新题 题意: 找出数组指定两个索引之间所有元素之和。

上善若水 977

Leetcode 303 Range Sum Query - Immutable

前缀和模版题,初始化前缀和数组并且求下标从left到right的元素和。

xxxmmc的博客 321

LeetCode 303. Range Sum Query - Immutable

LeetCode 303. Range Sum Query - Immutable (easy) 主要知识点:简单dp、构造数据结构 优先级:3(

温迪今天刷题了吗 431

Leetcode 303. Range Sum Query - Immutable

文章作者:Tyan 博客:noahsnail.com &amp;nbsp;|&amp;nbsp; CSDN &amp;nbsp;|&amp;nbsp; 简书 1. Description 2. Solution Version 1 class NumArray { public: NumArray(vector&amp;lt;int&amp;gt; nums) { this-&amp;gt;nums = nums;

SnailTyan 410

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)

指尖飞舞 5199

[LeetCode303] 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 sumRan

coder 进阶的专栏 969

[LeetCode] 303. Range Sum Query - Immutable

原题链接: https://leetcode.com/problems/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, ...

Ber03的博客 193
上一篇: LeetCode: 301. Remove Invalid Parentheses
下一篇: LeetCode: 304. Range Sum Query 2D - Immutable
IT技术小密圈
博客等级 码龄12年 1385粉丝 322原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值