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
相关推荐
程序员老陆19 分钟前
使用Qt+大华设备SDK预览大华摄像机视频
qt·算法·音视频·视频监控
罗超驿22 分钟前
9.优先级队列与堆:从底层原理到实战应用的完整指南
数据结构·算法
AI科技星1 小时前
光速螺旋时空曲率挠率拓扑统一场论——四大力全域闭环求导、精算验证与第一性原理完备证明
线性代数·算法·决策树·机器学习·常温超导·ai科技星
牧以南歌〆1 小时前
数据结构<三>单循环链表
c语言·数据结构·算法·链表
liuzhijie-06141 小时前
Codeforces 2245 D2 / E / F 题解
算法
薛定e的猫咪2 小时前
在 vibe coding开发项目过程中使用过的命令和概念整理
人工智能·学习·算法·开源
listening7772 小时前
《从算法到落地:基于HarmonyOS API 23的端侧图像推理实战》
算法·华为·harmonyos
Tisfy2 小时前
LeetCode 1979.找出数组的最大公约数:模拟(附手动gcd)
java·数学·算法·leetcode·题解·最大公约数
圣光SG2 小时前
Excel 函数大全
算法·excel
To_OC2 小时前
LC 79 单词搜索:都说这是回溯入门题,我却连错三回
javascript·算法·leetcode