博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode-724-Find Pivot Index]
阅读量:6608 次
发布时间:2019-06-24

本文共 1303 字,大约阅读时间需要 4 分钟。

Given an array of integers nums, write a method that returns the "pivot" index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

Example 1:

Input: nums = [1, 7, 3, 6, 5, 6]Output: 3Explanation: The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.Also, 3 is the first index where this occurs.

 

Example 2:

Input: nums = [1, 2, 3]Output: -1Explanation: There is no index that satisfies the conditions in the problem statement.

 思路:

用两个数组left和right分别统计每一个位置左边和右边的累加和。

left[i]代表位置i左边的累加和,

right[i]代表位置i右边的累加和。

int pivotIndex(vector
& nums){ int n = nums.size(); if (n == 0 || n == 1)return -1; vector
left(n, 0), right(n, 0); for (int i = 1; i < n; i++) { left[i] = left[i - 1] + nums[i - 1]; } for (int i = n - 2; i >= 0; i--) { right[i] = right[i + 1] + nums[i + 1]; } for (int i = 0; i < n; i++) { if (right[i] == left[i])return i; } return -1;}

 

转载于:https://www.cnblogs.com/hellowooorld/p/7826186.html

你可能感兴趣的文章
安全运维之:Linux系统账户和登录安全
查看>>
【cocos2d-x从c++到js】17:使用FireFox进行JS远程调试
查看>>
Kafka Offset Storage
查看>>
深度学习笔记之CNN(卷积神经网络)基础
查看>>
JAVA设计模式之【原型模式】
查看>>
Hadoop 添加删除数据节点(datanode)
查看>>
33.8. slb configuration
查看>>
ext的window如何隐藏水平滚动条
查看>>
71.8. Run level shell script to start Oracle 10g services on RedHat Enterprise Linux (RHAS 4)
查看>>
SAP QM Transfer of Inspection Stock
查看>>
全新视觉| 数治省市:SAP大数据构想一切可能
查看>>
ORACLE expdp备份与ORA-31693、ORA-02354、ORA-02149
查看>>
SAP S/4 HANA新变化-信用管理
查看>>
doc-remote-debugging.html
查看>>
DBMS_STATS.GATHER_TABLE_STATS
查看>>
Java-单机版的书店管理系统(练习设计模块和思想_系列 五 )
查看>>
嵌入式 详解udev
查看>>
《C程序员:从校园到职场》出版预告(2):从“百花齐放”到“一枝独秀”
查看>>
Network Monitor 查询命令和MySQL命令
查看>>
好“戏”刚刚开幕 云计算逐步被认可
查看>>