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
相关推荐
学嵌入式的小杨同学15 分钟前
【嵌入式 C 语言高频考点】周测 + 期中真题解析:从基础语法到编程实战
c语言·数据结构·数据库·vscode·算法·面试
沉默-_-22 分钟前
力扣hot100双指针专题解析2(C++)
java·c++·算法·蓝桥杯·双指针
福楠23 分钟前
C++ | 红黑树
c语言·开发语言·数据结构·c++·算法
程序员杰哥24 分钟前
Pytest自动化测试框架实战
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
丝瓜蛋汤26 分钟前
Proof of the contraction mapping theorem
人工智能·算法
We་ct1 小时前
LeetCode 58. 最后一个单词的长度:两种解法深度剖析
前端·算法·leetcode·typescript
小袁顶风作案1 小时前
leetcode力扣——452. 用最少数量的箭引爆气球
学习·算法·leetcode·职场和发展
deep_drink1 小时前
【经典论文精读(一)】Isomap:非线性降维的全局几何框架(Science 2000)
人工智能·算法·机器学习
mjhcsp1 小时前
莫比乌斯反演总结
c++·算法
爱编码的傅同学2 小时前
【今日算法】LeetCode 25.k个一组翻转链表 和 43.字符串相乘
算法·leetcode·链表