前言
参加掘金社区一个刷题打卡的活动第2题,也是数组和字符串
中的第1道题。
描述
给你一个整数数组nums
,请编写一个能够返回数组 “中心下标” 的方法。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果数组不存在中心下标,返回-1
。如果数组有多个中心下标,应该返回最靠近左边的那一个。
注意:中心下标可能出现在数组的两端。
**难度:**简单
示例:
输入:nums = [1, 7, 3, 6, 5, 6]
输出:3
解释:
中心下标是 3 。
左侧数之和 (1 + 7 + 3 = 11),
右侧数之和 (5 + 6 = 11) ,二者相等。
提示:
nums
的长度范围为[0, 10000]
。- 任何一个
nums[i]
将会是一个范围在[-1000, 1000]
的整数。
解题思路
我的解题思路
- 遍历数组,求得数组的总和
- 第二次遍历数组,记录以遍历元素的总和,然后计算当前元素以后的元素的总和,如何两者相等,则返回当前元素的索引
- 第二次遍历结束后没有找到对应值,返回
-1
官方解题思路
和我的解题思路一致,哈哈
AC代码
Python3
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
num_of_nums = sum(nums)
nums_length = len(nums)
num_of_calculated_nums = 0
for i in range(nums_length):
if num_of_nums - nums[i] - num_of_calculated_nums == num_of_calculated_nums:
return i
else:
num_of_calculated_nums += nums[i]
return -1
JavaScript
var pivotIndex = function(nums) {
const total = nums.reduce((pValue, cValue) => {
return pValue + cValue
}, 0)
let calculatedSum = 0
for(let i = 0; i < nums.length; i++) {
if (total - calculatedSum - nums[i] == calculatedSum) {
return i
} else {
calculatedSum += nums[i]
}
}
return -1
};
总结
这道题的解题思路中涉及到一个思维方法:preSum
,中文名:前缀和。
假设提供了一个长度为n
的数值型数组a
,可以定义一个新的长度为n+1
的数组b
,并使得b[i] = sum(a[0,...,i-1])
且b[0]=0
,那么sum(a[i,...,j])=b[j + 1] - b[i]
。
举个例子:假设数组a = [1,3,2,5,7]
,那么它对应的preSum
数组b=[0,1,4,6,11,18]
,计算a[2:4]
的值可以通过计算b[4+1] - b[2]
来求得。
题外话:JavaScript中数组的reduce函数
reduce
函数对数组中的每个元素(按照索引升序执行)执行一个提供的reducer函数,将其结果汇总为单个返回。reduce
接受两个参数:第1个参数是一个回调函数,第2个参数是可选项,作为回调函数的第1个参数的初始值,如果没有提供,那么回调函数的第1个参数的初始值为数组的第1个元素。回调函数接收4个参数,分别是:
accumulator
:累加器累计回调的返回值currentValue
:数组当前处理的元素index
:可选参数,数组当前处理元素的索引值array
:可选参数,调用reduce
函数的数组
const a = [1, 3, 2, 5, 7]
const b = a.reduce((accumulator, currentValue) => {
console.log(accumulator + ',' + currentValue)
return accumulator + currentValue
})
// 输出
// 1,3
// 4,2
// 6,5
// 11,7
const a = [1, 3, 2, 5, 7]
const b = a.reduce((accumulator, currentValue) => {
console.log(accumulator + ',' + currentValue)
return accumulator + currentValue
}, 0)
// 输出
// 0,1
// 1,3
// 4,2
// 6,5
// 11,7
const a = [1, 3, 2, 5, 7]
const b = a.reduce((accumulator, currentValue) => {
console.log(accumulator + ',' + currentValue)
}, 0)
// 输出
// 0,1
// undefined,3
// undefined,2
// undefined,5
// undefined,7
const a = [1, 3, 2, 5, 7]
const b = a.reduce((accumulator, currentValue) => {
console.log(accumulator + ',' + currentValue)
return accumulator * currentValue
}, 1)
// 输出
// 1,1
// 1,3
// 3,2
// 6,5
// 30,7