給你一個整數(shù)數(shù)組 nums,請編寫一個能夠返回數(shù)組 “中心索引” 的方法。
(數(shù)組 中心索引 是數(shù)組的一個索引,其左側(cè)所有元素相加的和等于右側(cè)所有元素相加的和。)
如果數(shù)組不存在中心索引,返回 -1 。如果數(shù)組有多個中心索引,應(yīng)該返回最靠近左邊的那一個。
注意:中心索引可能出現(xiàn)在數(shù)組的兩端。
例子:
輸入:nums = [1, 7, 3, 6, 5, 6]
輸出:3
解釋:
索引 3 (nums[3] = 6) 的左側(cè)數(shù)之和 (1 + 7 + 3 = 11),與右側(cè)數(shù)之和 (5 + 6 = 11) 相等。
同時, 3 也是第一個符合要求的中心索引。
輸入:nums = [1, 2, 3]
輸出:-1
解釋:
數(shù)組中不存在滿足此條件的中心索引。
輸入:nums = [2, 1, -1]
輸出:0
解釋:
索引 0 左側(cè)不存在元素,視作和為 0 ;右側(cè)數(shù)之和為 1 + (-1) = 0 ,二者相等。
輸入:nums = [0, 0, 0, 0, 1]
輸出:4
解釋:
索引 4 左側(cè)數(shù)之和為 0 ;右側(cè)不存在元素,視作和為 0 ,二者相等。
代碼
未翻譯版
class Solution {
func pivotIndex(_ nums: [Int]) -> Int {
if nums.count < 2 {return -1}
var left = 0, right = nums.reduce(0, +)
for (index, item) in nums.enumerated() {
right -= item
if left == right {
return index
}
left += item
}
return -1;
}
}
翻譯版
class Solution {
func pivotIndex(_ nums: [Int]) -> Int {
// 數(shù)組元素小于2的直接彈出
if nums.count < 2 {return -1}
// 設(shè)置初始 左邊之和0, 右邊之和所有元素相加
var left = 0, right = nums.reduce(0, +)
// 循環(huán)數(shù)組
for (index, item) in nums.enumerated() {
// 每次循環(huán), 右邊和減去當前元素
right -= item
// 判斷左右之和是否相等
if left == right {
// 相等返回分割元素下標
return index
}
// 不相等繼續(xù)循環(huán), 留意左邊加上元素
left += item
}
// 循環(huán)結(jié)果如果不存在返回 -1
return -1;
}
}
題目來源:力扣(LeetCode) 感謝力扣爸爸 :)
IOS 算法合集地址