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
相关推荐
YGGP7 小时前
【Golang】LeetCode 32. 最长有效括号
算法·leetcode
自然常数e8 小时前
字符函数和字符串函数
c语言·算法·visual studio
leaves falling8 小时前
c语言分数求和
算法
Das18 小时前
【机器学习】01_模型选择与评估
人工智能·算法·机器学习
星轨初途8 小时前
郑州轻工业大学2025天梯赛解题
c++·经验分享·笔记·算法·链表·剪枝
不忘不弃9 小时前
从字符串中提取数字
数据结构·算法
囊中之锥.9 小时前
《机器学习SVM从零到精通:图解最优超平面与软间隔实战》
算法·机器学习·支持向量机
顽强卖力9 小时前
第二章:什么是数据分析师?
笔记·python·职场和发展·学习方法
必胜刻10 小时前
复原 IP 地址(回溯算法)
tcp/ip·算法·深度优先
YGGP10 小时前
【Golang】LeetCode 5. 最长回文子串
算法·leetcode