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
相关推荐
怕浪猫13 分钟前
用了两年 AI 编程工具后,我重新理解了什么是「资深工程师」
算法·面试·架构
hetao173383739 分钟前
2026-08-27~29 hetao1733837 的刷题记录
c++·算法
云淡风轻~窗明几净1 小时前
宇宙管理学猜想
算法·图论
春风解人意1 小时前
从零开始学习嵌入式P28----线程
c语言·学习·算法
luj_17681 小时前
合法避税与投资评估实战指南
c语言·开发语言·网络·经验分享·算法
ychqsq1 小时前
144.扎根
经验分享·职场和发展
Bruce_Liuxiaowei2 小时前
驴滑块拼图游戏:从19世纪的纸片谜题到数学博弈论
人工智能·算法
一直C2 小时前
Linux系统编程|信号进阶 + SystemV IPC(消息队列、共享内存)
linux·c语言·开发语言·算法·青少年编程·vim
鹿角片ljp3 小时前
LeetCode 141. 环形链表|从 HashSet 到快慢指针 O (1) 空间最优解
算法·leetcode·链表
薛定e的猫咪3 小时前
(NeurIPS 2022)GraphGPS:MPNN 与全局注意力的融合之道
人工智能·深度学习·学习·算法