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
相关推荐
鑫鑫向栄11 分钟前
[蓝桥杯]堆的计数
数据结构·c++·算法·蓝桥杯·动态规划
緈福的街口22 分钟前
【leetcode】3. 无重复字符的最长子串
算法·leetcode·职场和发展
麦仓分享1 小时前
C++算法动态规划3
算法·动态规划
HEX9CF1 小时前
【Linux】awk 命令详解及使用示例:结构化文本数据处理工具
linux·chrome·算法
Cl_rown去掉l变成C2 小时前
第J3-1周:DenseNet算法 实现乳腺癌识别
人工智能·pytorch·算法
努力学习的小廉2 小时前
我爱学算法之—— 前缀和(中)
开发语言·redis·算法
保持学习ing2 小时前
黑马Java面试笔记之 集合篇(算法复杂度+ArrayList+LinkedList)
java·笔记·算法·面试
LunaGeeking2 小时前
三分算法与DeepSeek辅助证明是单峰函数
c语言·c++·算法·编程·信奥赛·ai辅助学习·三分
Darkwanderor2 小时前
数论——同余问题全家桶3 __int128和同余方程组
c++·算法·数论·中国剩余定理
Xyz_Overlord2 小时前
机器学习——聚类算法
算法·机器学习·聚类