当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

Kyndryl partnered with Oracle and Veritas

Naacl 2022 | TAMT: search the transportable Bert subnet through downstream task independent mask training

外部存储器

Semaphore of thread synchronization

American chips are hit hard again, and another chip enterprise after Intel will be overtaken by Chinese chips

External memory

EventLoop learning

Learning records of numpy Library

【OS命令注入】常见OS命令执行函数以及OS命令注入利用实例以及靶场实验—基于DVWA靶场

How to set postman to Chinese? (Chinese)
随机推荐
Firewall foundation Huawei H3C firewall web page login
JVM parameter setting and analysis
enable_if
MySQL locking mechanism and four isolation levels
JVM performance tuning and monitoring tools -- JPS, jstack, jmap, jhat, jstat, hprof
为什么 Oracle 云客户必须在Oracle Cloud 季度更新发布后自行测试?
CMOS level circuit analysis
以前国产手机高傲定价扬言消费者爱买不买,现在猛降两千求售
After the deployment is created, the pod problem handling cannot be created
Principle Comparison and analysis of mechanical hard disk and SSD solid state disk
Redis 主从复制、哨兵模式、Cluster集群
深入理解位运算
Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance
[business security-04] universal user name and universal password experiment
事务的四大特性
机械硬盘和ssd固态硬盘的原理对比分析
MySQL index and its classification
芯片供给过剩之际,进口最多的中国继续减少进口,美国芯片慌了
OpenSSF安全计划:SBOM将驱动软件供应链安全
Embedded development: embedded foundation callback function