当前位置:网站首页>一维数组动态和问题答记
一维数组动态和问题答记
2022-08-10 19:05:00 【小问号我们是朋友】
给定题干:
给你一个数组 nums 。数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]…nums[i]) 。
请返回 nums 的动态和。
题目来源:
力扣(LeetCode)
1.示例
代码如下(示例):
输入:nums = [1,1,1,1,1]
输出:[1,2,3,4,5]
解释:动态和计算过程为 [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1] 。
2.解答与注记
代码如下(Java):
class Solution {
public int[] runningSum(int[] nums) {
int len = nums.length;
//解法1
//新建一个空的数组
int[] resSum = new int[len];
//遍历给定数组,数组的第一个元素直接放入新数组中,后面的元素每次都与新数组的上一个元素相加。
for(int i = 0; i < len; i++) {
if(i == 0) {
resSum[i] = nums[i];
}else {
resSum[i] = resSum[i - 1] + nums[i];
}
}
return resSum;
//解法2
//在原数组的基础上做原地遍历修改,第一个元素不做修改,后续的元素每次加上上一个元素。
for(int i = 0; i < len; i++) {
if(i != 0) {
nums[i] += nums[i - 1];
}
}
return nums;
}
}
总结
以上就是今天要讲的内容,本文介绍了一维数组动态和的解决方法,在此备忘以供参考。
边栏推荐
- FPGA:基础入门按键控制蜂鸣器
- The servlet mapping path matching resolution
- 我们用48h,合作创造了一款Web游戏:Dice Crush,参加国际赛事
- Redis persistence mechanism
- 云渲染的应用正在扩大,越来越多的行业需要可视化服务
- WCF and TCP message communication practice, c # 】 【 realize group chat function
- Metasploit——渗透攻击模块(Exploit)
- 多种深度模型实现手写字母MNIST的识别(CNN,RNN,DNN,逻辑回归,CRNN,LSTM/Bi-LSTM,GRU/Bi-GRU)
- Qt学习第三天
- 这7个自动化办公模版 教你玩转表格数据自动化
猜你喜欢
【OpenCV】-物体的凸包
什么是企业知识库?有什么作用?如何搭建?
The servlet mapping path matching resolution
2022 Hangdian Multi-School Seven Black Magic (Sign-in)
多种深度模型实现手写字母MNIST的识别(CNN,RNN,DNN,逻辑回归,CRNN,LSTM/Bi-LSTM,GRU/Bi-GRU)
【Knowledge Sharing】What is SEI in the field of audio and video development?
几行深度学习代码设计包含功能位点的候选免疫原、酶活性位点、蛋白结合蛋白、金属配位蛋白
[Teach you how to make a small game] Write a function with only a few lines of native JS to play sound effects, play BGM, and switch BGM
第14章_MySQL事务日志
力扣150-逆波兰表达式求值——栈实现
随机推荐
[Teach you how to do mini-games] How to lay out the hands of Dou Dizhu?See what the UP master of the 250,000 fan game area has to say
手把手教你Charles抓包工具使用
【知识分享】在音视频开发领域中SEI到底是个啥?
mysql 中大小写问题
选择是公有云还或是私有云,这很重要吗?
Random函数用法
这7个自动化办公模版 教你玩转表格数据自动化
补坑求逆序对
【初学必备】3d游戏建模入门基础知识
Optimizing Bloom Filter: Challenges, Solutions, and Comparisons论文总结
云渲染的应用正在扩大,越来越多的行业需要可视化服务
Unity_Stack<T>()的应用(多个次级界面后的返回逻辑)
[教你做小游戏] 只用几行原生JS,写一个函数,播放音效、播放BGM、切换BGM
DefaultSelectStrategy NIOEventLoop执行策略
常量
C#/VB.NET 将PDF转为PDF/X-1a:2001
When selecting a data destination when creating an offline synchronization node - an error is reported in the table, the database type is adb pg, what should I do?
Common ports and services
从 Delta 2.0 开始聊聊我们需要怎样的数据湖
LeetCode·283.移除零·双指针