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
相关推荐
2301_7644413311 分钟前
python实现罗斯勒吸引子(Rössler Attractor)
开发语言·数据结构·python·算法·信息可视化
码农三叔15 分钟前
(7-3)自动驾驶中的动态环境路径重规划:实战案例:探险家的行进路线
人工智能·算法·机器学习·机器人·自动驾驶
飞Link29 分钟前
【Water】数据增强中的数据标注、数据重构和协同标注
算法·重构·数据挖掘
漫随流水38 分钟前
leetcode算法(559.N叉树的最大深度)
数据结构·算法·leetcode·二叉树
池塘的蜗牛39 分钟前
NR PDSCH和CSI 正交导频设计
算法
CoovallyAIHub1 小时前
仅192万参数的目标检测模型,Micro-YOLO如何做到目标检测精度与效率兼得
深度学习·算法·计算机视觉
sali-tec1 小时前
C# 基于OpenCv的视觉工作流-章10-中值滤波
图像处理·人工智能·opencv·算法·计算机视觉
爱编程的小吴1 小时前
【力扣练习题】151. 反转字符串中的单词
java·算法·leetcode