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
相关推荐
式5167 小时前
线性代数(七)主变量与特解
线性代数·算法
业精于勤的牙13 小时前
浅谈:算法中的斐波那契数(二)
算法·职场和发展
不穿格子的程序员13 小时前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表
liuyao_xianhui14 小时前
寻找峰值--优选算法(二分查找法)
算法
dragoooon3414 小时前
[hot100 NO.19~24]
数据结构·算法
Tony_yitao15 小时前
15.华为OD机考 - 执行任务赚积分
数据结构·算法·华为od·algorithm
C雨后彩虹16 小时前
任务总执行时长
java·数据结构·算法·华为·面试
风筝在晴天搁浅16 小时前
代码随想录 463.岛屿的周长
算法
一个不知名程序员www16 小时前
算法学习入门---priority_queue(C++)
c++·算法