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
相关推荐
liu****几秒前
11.字符函数和字符串函数(二)
c语言·开发语言·数据结构·c++·算法
灵犀坠8 分钟前
前端高频知识点汇总:从手写实现到工程化实践(面试&开发双视角)
开发语言·前端·javascript·tcp/ip·http·面试·职场和发展
机器学习之心12 分钟前
MATLAB基于改进蜣螂优化算法的磨削参数低碳优化
算法·matlab·基于改进蜣螂优化算法·磨削参数低碳优化
IT_Octopus20 分钟前
算法题:力扣 热题100道 中等难度128. 最长连续序列
算法·leetcode
浅川.2522 分钟前
xtuoj 方程
算法
Swift社区24 分钟前
LeetCode 441 - 排列硬币
算法·leetcode·职场和发展
solicitous27 分钟前
第一章 信息化发展
职场和发展
TL滕27 分钟前
从0开始学算法——第七天(快速排序算法练习)
笔记·学习·算法·排序算法
MicroTech202529 分钟前
MLGO微算法科技 D-S融合算法技术发布,助力脑机接口迈向实用化
大数据·科技·算法
Q741_14730 分钟前
C++ 栈 模拟 力扣 844. 比较含退格的字符串 题解 每日一题
c++·算法·leetcode·模拟·