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
相关推荐
zhuzhuxia⌓‿⌓12 分钟前
线性表的顺序和链式存储
数据结构·c++·算法
未知陨落32 分钟前
LeetCode:95.编辑距离
算法·leetcode
杨小码不BUG1 小时前
小鱼的数字游戏:C++实现与算法分析(洛谷P1427)
c++·算法·数组·信奥赛·csp-j/s
高山有多高1 小时前
栈:“后进先出” 的艺术,撑起程序世界的底层骨架
c语言·开发语言·数据结构·c++·算法
YouEmbedded1 小时前
解码查找算法与哈希表
数据结构·算法·二分查找·散列表·散列查找·线性查找
greentea_20132 小时前
Codeforces Round 65 C. Round Table Knights(71)
c语言·开发语言·算法
小秋学嵌入式-不读研版2 小时前
C61-结构体数组
c语言·开发语言·数据结构·笔记·算法
可触的未来,发芽的智生2 小时前
触摸未来2025.10.04:当神经网络拥有了内在记忆……
人工智能·python·神经网络·算法·架构
与己斗其乐无穷2 小时前
刷题记录(11)map和set的简单使用
算法
夜月yeyue3 小时前
个人写HTOS移植shell
c++·mcu·算法·性能优化·架构·mfc