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 sumrindex-1 == rsumindex.

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
相关推荐
明月_清风2 分钟前
位图与布隆过滤器:海量数据下的"存在性判断"艺术
前端·后端·算法
Rnan-prince5 分钟前
堆与TopK · 从零到通透 —— 9 节全系列复盘
python·算法
明月_清风9 分钟前
Hash 表从入门到精通:Go 实战与工程细节
前端·后端·算法
熊野君12 分钟前
第 7 章 AI时代产品经理新增能力
大数据·人工智能·经验分享·职场和发展·产品经理
nbsaas-boot41 分钟前
多智能体系统的架构边界:任务编排、共享状态与故障隔离设计
人工智能·算法·动态规划
wuyk5551 小时前
12.归并排序:分治思想的稳定排序算法
开发语言·数据结构·算法·排序算法
吴声子夜歌1 小时前
ApacheCommons——commons-text(模板替换与文本算法)
java·开发语言·算法·apache
JiNan.YouQuan.Soft1 小时前
数值计算引擎:计算固体力学
人工智能·算法·机器学习
和裕2 小时前
光伏储能定制加强型瓦楞纸箱:降低组件运输隐裂率与售后损耗的核心价值
大数据·运维·网络·人工智能·算法
Pointer Pursuit2 小时前
C++11特性(二)
前端·c++·算法