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
相关推荐
Jerry16 分钟前
LeetCode 78. 子集
算法
DuHz1 小时前
论文解读:用于数据分析的极值点对称模态分解方法 (Extreme-point Symmetric Mode Decomposition,ESMD)
论文阅读·算法·信息与通信·信号处理
菜小麒1 小时前
面试问题-01
面试·职场和发展
HZZD_HZZD1 小时前
用电负荷聚类分析实战:基于`scikit-learn`的`K-Means`与`DBSCAN`双算法对比、`PCA`降维可视化与智能电表负荷画像全流程
算法·scikit-learn·kmeans
MIngYaaa5201 小时前
2026暑期牛客多校1 2026-7-17
数据结构·算法
wabs6661 小时前
关于图论【卡码网107.寻找存在的路线的思考】
数据结构·算法·图论
半兽先生2 小时前
大模型技术开发与应用——4.大模型提示词工程实战
人工智能·算法
wuminyu2 小时前
JUC组件逐层剥离与深度剖析
java·linux·c语言·jvm·c++·算法
XiaoYu1__2 小时前
算法进阶·其二:用欧拉路径解决“一笔画”问题并建模转化De Bruijn序列的构造问题
c++·笔记·算法·欧拉路径
城管不管2 小时前
重生——第五次面试2026.8.1一面
java·数据库·后端·ai·面试·职场和发展·agent