Daily LeetCode 724. Find Pivot Index
https://leetcode.com/problems/find-pivot-index/
Easy
问题描述:
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:
1 | Input: |
Example 2:
1 | Input: |
Note:
- The length of
nums
will be in the range[0, 10000]
. - Each element
nums[i]
will be an integer in the range[-1000, 1000]
.
题目分析:
给定一个数组,我们需要找到一个分割点,使得分割点两边的和相等,如果存在多个点,则返回最左边的,如果不存在,则返回-1
。
我们只需要一次遍历,就能够解决这个问题。初始状态下的index
为0
,此时leftSum=0, rightSum=sum(nums)
,在遍历过程中,不断更新leftSum, rightSum
,就可以找到最左边的分割点。
以题目中所给例子为例,遍历过程中和的更新情况如下:
1 | index: 0 , leftSum: 0 , rightSum: 27 |
代码:
1 | class Solution(object): |