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
相关推荐
写个博客37 分钟前
暑假算法日记第二天
算法
ChaITSimpleLove1 小时前
.NET9 实现排序算法(MergeSortTest 和 QuickSortTest)性能测试
算法·排序算法·.net·benchmarkdotnet·datadog.trace
CVer儿1 小时前
svd分解求旋转平移矩阵
线性代数·算法·矩阵
Owen_Q1 小时前
Denso Create Programming Contest 2025(AtCoder Beginner Contest 413)
开发语言·算法·职场和发展
Wilber的技术分享2 小时前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
Tanecious.2 小时前
LeetCode 876. 链表的中间结点
算法·leetcode·链表
Wo3Shi4七3 小时前
哈希冲突
数据结构·算法·go
呆呆的小鳄鱼3 小时前
cin,cin.get()等异同点[面试题系列]
java·算法·面试
Touper.3 小时前
JavaSE -- 泛型详细介绍
java·开发语言·算法
sun0077003 小时前
std::forward作用
开发语言·c++·算法