当前位置:网站首页>Leetcode 724. 寻找数组的中心下标(可以,一次过)
Leetcode 724. 寻找数组的中心下标(可以,一次过)
2022-06-27 13:51: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 。
提示:
- 1 <= nums.length <= 10^4
- -1000 <= nums[i] <= 1000
Code:
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int left=0;
int right=0;
for(int i=0;i<nums.size();i++)
{
if(i!=0)
left=accumulate(nums.begin(),nums.begin()+i,0);
right=accumulate(nums.begin()+i+1,nums.end(),0);
// cout<<left<<" "<<right<<endl;
if(left==right)
return i;
}
return -1;
}
};
边栏推荐
- Dynamic Networks and Conditional Computation论文简读和代码合集
- Cesium realizes satellite orbit detour
- enable_if
- 【业务安全-01】业务安全概述及测试流程
- [business security-02] business data security test and example of commodity order quantity tampering
- 类模板中可变参的逐步展开
- CMOS级电路分析
- MySQL index and its classification
- 简析国内外电商的区别
- Type 'image' is not a subtype of type 'imageprovider < object > solution
猜你喜欢

对半查找(折半查找)

Redis 主从复制、哨兵模式、Cluster集群

重读经典:《The Craft of Research(1)》

线程同步之信号量

IJCAI 2022 | greatly improve the effect of zero sample learning method with one line of code. Nanjing Institute of Technology & Oxford proposed the plug and play classifier module

隐私计算FATE-离线预测

Kyndryl与Oracle和Veritas达成合作

How to select cross-border e-commerce multi merchant system

Kyndryl partnered with Oracle and Veritas

Deep understanding of bit operations
随机推荐
Shell concise tutorial
Type 'image' is not a subtype of type 'imageprovider < object > solution
crane:字典项与关联数据处理的新思路
Prometheus 2.26.0 new features
How to select cross-border e-commerce multi merchant system
Yyds dry goods inventory solution sword finger offer: cut rope (advanced version)
剑指 Offer II 039. 直方图最大矩形面积 单调栈
mysql 锁机制与四种隔离级别
Li Kou's 81st biweekly match
[安洵杯 2019]Attack
Kotlin函数使用示例教程
Dynamic Networks and Conditional Computation论文简读和代码合集
External memory
Why must Oracle cloud customers self test after the release of Oracle cloud quarterly update?
[business security-02] business data security test and example of commodity order quantity tampering
芯片供给过剩之际,进口最多的中国继续减少进口,美国芯片慌了
Learning records of numpy Library
Number of printouts (solved by recursive method)
类模板中可变参的逐步展开
CCID Consulting released the database Market Research Report on key application fields during the "14th five year plan" (attached with download)