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
相关推荐
Wilber的技术分享38 分钟前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病41 分钟前
Problem L. ZZUPC
c++·数学·算法·前缀和
软件测试媛2 小时前
软件测试常见的面试题(46道)
功能测试·面试·职场和发展
梯度下降中2 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy2 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl200209252 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
靴子学长3 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv
寒秋花开曾相惜3 小时前
(学习笔记)3.8 指针运算(3.8.3 嵌套的数组& 3.8.4 定长数组)
java·开发语言·笔记·学习·算法
Гений.大天才3 小时前
2026年计算机领域的年度主题与范式转移
算法
njidf3 小时前
C++与Qt图形开发
开发语言·c++·算法