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
相关推荐
mit6.8241 小时前
前后缀分解
算法
你好,我叫C小白2 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林4 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway4 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No75 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区5 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫5 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****5 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者6 小时前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶
程序员大雄学编程7 小时前
「深度学习笔记4」深度学习优化算法完全指南:从梯度下降到Adam的实战详解
笔记·深度学习·算法·机器学习