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
相关推荐
进击的小头17 分钟前
第15篇:MPC的发展方向及展望
python·算法
We་ct25 分钟前
LeetCode 35. 搜索插入位置:二分查找的经典应用
前端·算法·leetcode·typescript·个人开发
IT猿手37 分钟前
基于 ZOH 离散化与增量 PID 的四旋翼无人机轨迹跟踪控制研究,MATLAB代码
开发语言·算法·matlab·无人机·动态路径规划·openclaw
A923A41 分钟前
【洛谷刷题 | 第五天】
算法·字符串·递归·洛谷
Navigator_Z1 小时前
LeetCode //C - 990. Satisfiability of Equality Equations
c语言·算法·leetcode
bbbb3651 小时前
图算法的最优路径搜索与边界约束建模的技术7
算法
東雪木1 小时前
编程算法学习——栈与队列算法
学习·算法·排序算法
CSDN_Colinw1 小时前
C++中的工厂方法模式
开发语言·c++·算法
liulilittle1 小时前
范围随机算法实现
开发语言·c++·算法·lua·c·js
2401_857918292 小时前
C++中的访问者模式实战
开发语言·c++·算法