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
相关推荐
m0_736919103 小时前
C++中的委托构造函数
开发语言·c++·算法
小小小小王王王3 小时前
洛谷-P1886 【模板】单调队列 / 滑动窗口
c++·算法
网络安全-杰克3 小时前
Jmeter压力测试工具安装与使用
自动化测试·软件测试·测试工具·jmeter·职场和发展
PPPPPaPeR.4 小时前
光学算法实战:深度解析镜片厚度对前后表面折射/反射的影响(纯Python实现)
开发语言·python·数码相机·算法
看我干嘛!4 小时前
python第五次作业
算法
历程里程碑4 小时前
Linux 库
java·linux·运维·服务器·数据结构·c++·算法
Sheep Shaun4 小时前
如何让一个进程诞生、工作、终止并等待回收?——探索Linux进程控制与Shell的诞生
linux·服务器·数据结构·c++·算法·shell·进程控制
Pluchon4 小时前
硅基计划4.0 简单模拟实现AVL树&红黑树
java·数据结构·算法
June bug4 小时前
【PMP】敏捷Scrum实践
经验分享·职场和发展·学习方法·scrum
生锈的键盘4 小时前
推荐算法实践:交叉特征的理解
算法