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
相关推荐
民乐团扒谱机3 小时前
【微实验】谐波乘积谱(HPS)算法深度解析:原理、数学与代码实现
开发语言·人工智能·python·算法·语音识别·音乐
Nil2083 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵
忍冬k4 小时前
DeepSeek harness安装指南
java·开发语言·数据结构·c++·算法
何以解忧,唯有..5 小时前
预订酒店问题
算法
No8g攻城狮5 小时前
【算法】什么是 DFS 与 BFS 及他们的区别
算法·深度优先·宽度优先
zww89491115 小时前
家政派单系统实战指南:从需求分析到智能调度算法落地
算法·需求分析
手写码匠5 小时前
华为云Flexus+DeepSeek征文|Dify 多 Agent 评测实战:用 DeepSeek-R1 当裁判,打造多智能体系统的自动化质量保障体系
人工智能·深度学习·算法·aigc
ZC跨境爬虫6 小时前
LeetCode 88. 合并两个有序数组(双指针详解 + Java Python 实现)
java·python·算法·leetcode
Nil2086 小时前
leetcode 238除了自身以外数组的乘积
数据结构·算法·leetcode
土司大王6 小时前
LeetCode hot100——最长连续序列
数据结构·算法·leetcode