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
相关推荐
6Hzlia2 分钟前
【Hot 100 刷题计划】 LeetCode 141. 环形链表 | C++ 哈希表直觉解法
c++·leetcode·链表
dinl_vin4 分钟前
LangChain 系列·(四):RAG 基础——给大模型装上“外脑“
人工智能·算法·langchain
探物 AI30 分钟前
【感知·医学分割】当 YOLOv11 杀入医学赛道:先检测后分割的级联架构
算法·yolo·计算机视觉·架构
隔壁大炮37 分钟前
Day06-08.CNN概述介绍
人工智能·pytorch·深度学习·算法·计算机视觉·cnn·numpy
白云千载尽37 分钟前
前馈与反馈——经典控制理论中的基础概念
人工智能·算法
炽烈小老头1 小时前
【每日天学习一点算法 2026/04/27】缺失的第一个正数
学习·算法
南宫萧幕1 小时前
HEV 智能能量管理实战:从 MPC/PPO 理论解析到 Python-Simulink 联合仿真闭环全流程
开发语言·python·算法·matlab·控制
啦啦啦_99991 小时前
1. 一元/多元线性回归之 正规方程求解法
算法·回归·线性回归
ECT-OS-JiuHuaShan1 小时前
整体论体系定理,全球开放,无法绕过
人工智能·科技·学习·算法·生活
贾斯汀玛尔斯2 小时前
每天学一个算法--BM25(Okapi BM25)
算法