Leetcode 724. Find Pivot Index

Problem

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Algorithm

First get the sum of the first i-items and last i-items in lsum and rsum, then find the pivot index with sumrindex-1 == rsumindex.

Code

python3 复制代码
class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        nlen = len(nums)
        lsum = [0] * (nlen+1)
        rsum = [0] * (nlen+1)
        for i in range(nlen):
            lsum[i+1] = lsum[i] + nums[i]
            rsum[nlen-1-i] = rsum[nlen-i] + nums[nlen-1-i]

        for i in range(1, nlen+1):
            if lsum[i-1] == rsum[i]:
                return i-1
        return -1
相关推荐
菜鸡爱玩2 小时前
线性代数矩阵相乘
线性代数·算法·矩阵
devilnumber5 小时前
Java 递归算法 详解 + 核心要点 + 实战运用 + 避坑指南
java·开发语言·算法
‎ദ്ദിᵔ.˛.ᵔ₎7 小时前
双指针、滑动窗口、前缀和、二分查找 算法
算法
顾北顾7 小时前
多头注意力机制
人工智能·深度学习·算法
H178535090967 小时前
SolidWorks_基于草图的实体特征20_特征错误排查
算法·3d建模·solidworks
hujinyuan201608 小时前
2025年12月中国电子学会青少年机器人技术等级考试试卷(二级) 真题+答案
人工智能·算法·机器人
bIo7lyA8v8 小时前
算法复杂度评估的实验统计方法与可视化的技术8
算法
李老师讲编程9 小时前
中国电子学会图形化2020.12月Scratch三级考级题
算法·scratch·信息学奥赛·图形化编程·scratch素材
退休倒计时9 小时前
【每日一题】LeetCode 53. 最大子数组和 TypeScript
数据结构·算法·leetcode·typescript