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 sumr[index-1] == rsum[index].

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
相关推荐
想做功的洛伦兹力12 分钟前
2026/2/13日打卡
算法
仟濹6 分钟前
【算法打卡day7(2026-02-12 周四)算法:BFS and BFS】 3_卡码网107_寻找存在的路线_并查集
数据结构·算法·图论·宽度优先
YuTaoShao7 分钟前
【LeetCode 每日一题】3713. 最长的平衡子串 I ——(解法二)暴力枚举 + 优化
算法·leetcode·职场和发展
蜡笔小马8 分钟前
20.Boost.Geometry 中常用空间算法详解:crosses、densify、difference 与离散距离度量
c++·算法·boost
rgb2gray18 分钟前
优多元分层地理探测器模型(OMGD)研究
人工智能·算法·机器学习·回归·gwr
码农三叔41 分钟前
《卷2:人形机器人的环境感知与多模态融合》
人工智能·嵌入式硬件·算法·机器人·人形机器人
福大大架构师每日一题1 小时前
2026-01-15:下一个特殊回文数。用go语言,给定一个整数 n,求出一个比 n 更大的最小整数,该整数需要满足两条规则: 1. 它的十进制表示从左到右与从右到左完全一致(即读起来是对称的)。 2
python·算法·golang
努力进修1 小时前
算法刷题无边界!Hello-Algo+cpolar 随时随地想学就学
算法·cpolar
寻寻觅觅☆1 小时前
东华OJ-基础题-127-我素故我在(C++)
开发语言·c++·算法
ab1515171 小时前
2.13完成101、102、89
开发语言·c++·算法