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
相关推荐
吃好睡好便好13 小时前
用while循环语句求和
开发语言·学习·算法·matlab·信息可视化
王璐WL13 小时前
【C语言入门级教学】函数的概念2
c语言·数据结构·算法
不知名的忻14 小时前
B 树与 B+ 树:面试完全指南
b树·算法·面试·b+树
运筹vivo@15 小时前
2657. 找到两个数组的前缀公共数组 | 难度:中等
算法·leetcode·职场和发展·哈希表
索木木15 小时前
NCCL SHARP 和 TREE算法
java·服务器·算法
Raink老师15 小时前
【AI面试临阵磨枪-59】企业内部 AI 系统权限、数据隔离、审计设计
人工智能·面试·职场和发展
心中有国也有家16 小时前
hccl 架构拆解:昇腾集合通信库到底在做什么?
人工智能·经验分享·笔记·分布式·算法·架构
小O的算法实验室16 小时前
2026年MCS,Q-learning增强MOPSO与改进DWA融合算法+复杂三维地形下特定移动机器人动态路径规划
算法
JAVA社区17 小时前
Java进阶全套教程(四)—— SpringMVC框架详解
java·开发语言·spring·面试·职场和发展
Peter·Pan爱编程17 小时前
10. new_delete 不是 malloc_free 的包装
c++·人工智能·算法