原题是:
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: 3
Explanation:
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: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
思路是:
我的思路一般有点偏宏观,会想到整个数组的和,以及左右的数组的和。
有的时候需要进入微观的过程,来发现思路。
联想到暴力解法是遍历每个元素,将它左边的和,与右边的和,相比较。
这个方法一眼就能看出有许多重复,那么就要想,前面一个元素它左边的和,能否给后面一个元素的左边的和,提供一些已有的便利呢。
所以思路就出来了:
当检查下一个元素的时候,只要把上一个被检查的元素的值加到左边的和中,并把当前被检查的元素从右边的和中减去。就不用再重新计算这个元素左边所有的和,和右边所有的和。
代码是:
class Solution:
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
Left = 0
Right = sum(nums)
for i in range(len(nums)):
if i == 0:
Right = Right - nums[0]
else:
Left = Left + nums[i-1]
Right = Right - nums[i]
if Left == Right:
return i
return -1
网友评论