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
相关推荐
forest_093 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
纪念 2294 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
杨逢昌工厂6S管理6 小时前
150-杨逢昌一线现场诊断笔记:越管一线越抵触背后的熵增机理与基准化治理
经验分享·笔记·职场和发展·学习方法
文丑颜不良啊7 小时前
LeetCode2761~2780题目解析
java·leetcode
jyOverQ7 小时前
从零学 JVM(六):垃圾回收算法详解——标记清除、标记复制与标记整理
jvm·算法
严肃小白兔9 小时前
第 06/24 期:神经网络的反向传播算法:从链式法则到梯度计算
人工智能·神经网络·算法
落羽的落羽9 小时前
【C++】C++17的主要特性
linux·服务器·开发语言·c++·算法·机器学习
文丑颜不良啊10 小时前
LeetCode2841~2860题目解析
java·leetcode
【心态好不摆烂】10 小时前
数据结构基础精讲3
数据结构·算法