当前位置:网站首页>【剑指offer】剑指 Offer II 012. 左右两边子数组的和相等
【剑指offer】剑指 Offer II 012. 左右两边子数组的和相等
2022-07-07 17:37:00 【瑾怀轩】
给你一个整数数组 nums ,请计算数组的 中心下标 。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。
示例 1:
输入:nums = [1,7,3,6,5,6]
输出:3
解释:
中心下标是 3 。
左侧数之和 sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 ,
右侧数之和 sum = nums[4] + nums[5] = 5 + 6 = 11 ,二者相等。
示例 2:
输入:nums = [1, 2, 3]
输出:-1
解释:
数组中不存在满足此条件的中心下标。
示例 3:
输入:nums = [2, 1, -1]
输出:0
解释:
中心下标是 0 。
左侧数之和 sum = 0 ,(下标 0 左侧不存在元素),
右侧数之和 sum = nums[1] + nums[2] = 1 + -1 = 0 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/tvdfij
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java:
class Solution {
public Integer getArraysum(int[] arr){
int total = 0;
for(int i =0 ; i < arr.length;i++){
total += arr[i];
}
return total;
}
public int pivotIndex(int[] nums) {
//前缀和思想:计算数组中元素和total,从左至右遍历,当前元素为num[i], 判断是不是中心下标条件为:sum == total - num[i] - sum ;
int total = getArraysum(nums);
//使用sum存储左边和
int sum = 0;
//使用i指针开始遍历
for(int i =0 ; i<nums.length ;i++){
if(sum == (total - nums[i] - sum)){
return i;
}
sum += nums[i];
}
return -1;
}
}边栏推荐
猜你喜欢

2022.07.02

9 atomic operation class 18 Rohan enhancement

索引总结(突击版本)

648. 单词替换

2022.07.05

Kirin Xin'an joins Ningxia commercial cipher Association

How to estimate the value of "not selling pens" Chenguang?

华南X99平台打鸡血教程

Tips and tricks of image segmentation summarized from 39 Kabul competitions

微信公众号OAuth2.0授权登录并显示用户信息
随机推荐
Le PGR est - il utile au travail? Comment choisir une plate - forme fiable pour économiser le cœur et la main - d'œuvre lors de la préparation de l'examen!!!
Nunjuks template engine
现在股票开户可以直接在网上开吗?安全吗。
The research group of the Hunan Organizing Committee of the 24th China Association for science and technology visited Kirin Xin'an
实训九 网络服务的基本配置
ASP.NET幼儿园连锁管理系统源码
Experiment 1 of Compilation Principle: automatic implementation of lexical analyzer (Lex lexical analysis)
Make this crmeb single merchant wechat mall system popular, so easy to use!
最长公共前缀(leetcode题14)
怎么在手机上买股票开户 股票开户安全吗
R语言ggplot2可视化:使用ggpubr包的ggstripchart函数可视化分组点状条带图(dot strip plot)、设置position参数配置不同分组数据点的分离程度
Unable to link the remote redis server (solution 100%
Is PMP beneficial to work? How to choose a reliable platform to make it easier to prepare for the exam!!!
5billion, another master fund was born in Fujian
杰理之测试盒配置声道【篇】
el-upload上传组件的动态添加;el-upload动态上传文件;el-upload区分文件是哪个组件上传的。
LC: string conversion integer (ATOI) + appearance sequence + longest common prefix
Research and practice of super-resolution technology in the field of real-time audio and video
Command mode - unity
Pasqal首席技术官:模拟量子计算率先为工业带来量子优势