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
相关推荐
Touper.14 分钟前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun00770016 分钟前
std::forward作用
开发语言·c++·算法
JoernLee34 分钟前
机器学习算法:支持向量机SVM
人工智能·算法·机器学习
V我五十买鸡腿43 分钟前
顺序栈和链式栈
c语言·数据结构·笔记·算法
我爱一条柴ya1 小时前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程
三维重建-光栅投影3 小时前
VS中将cuda项目编译为DLL并调用
算法
课堂剪切板5 小时前
ch03 部分题目思路
算法
山登绝顶我为峰 3(^v^)36 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.7 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
森焱森9 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机