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
相关推荐
mit6.8246 分钟前
几何|阻碍链
算法
有一个好名字8 分钟前
力扣-小行星碰撞
算法·leetcode·职场和发展
MM_MS8 分钟前
Halcon图像锐化和图像增强、窗口的相关算子
大数据·图像处理·人工智能·opencv·算法·计算机视觉·视觉检测
lamentropetion16 分钟前
E - Equal Tree Sums CF1656E
算法
代码游侠17 分钟前
应用——智能配电箱监控系统
linux·服务器·数据库·笔记·算法·sqlite
2301_8008951019 分钟前
hh的蓝桥杯每日一题--前缀和
职场和发展·蓝桥杯
Xの哲學33 分钟前
Linux Platform驱动深度剖析: 从设计思想到实战解析
linux·服务器·网络·算法·边缘计算
逑之39 分钟前
C语言笔记11:字符函数和字符串函数
c语言·笔记·算法
栈与堆1 小时前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
不知名XL1 小时前
day20 回溯算法part02
算法