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
相关推荐
ytttr8734 小时前
隐马尔可夫模型(HMM)MATLAB实现范例
开发语言·算法·matlab
AlenTech4 小时前
160. 相交链表 - 力扣(LeetCode)
数据结构·leetcode·链表
点云SLAM4 小时前
凸优化(Convex Optimization)理论(1)
人工智能·算法·slam·数学原理·凸优化·数值优化理论·机器人应用
jz_ddk5 小时前
[学习] 卫星导航的码相位与载波相位计算
学习·算法·gps·gnss·北斗
放荡不羁的野指针5 小时前
leetcode150题-动态规划
算法·动态规划
sin_hielo5 小时前
leetcode 1161(BFS)
数据结构·算法·leetcode
一起努力啊~5 小时前
算法刷题-二分查找
java·数据结构·算法
水月wwww5 小时前
【算法设计】动态规划
算法·动态规划
零售ERP菜鸟5 小时前
当业务战略摇摆不定:在变化中锚定不变的IT架构之道
信息可视化·职场和发展·架构·创业创新·学习方法·业界资讯
码农水水6 小时前
小红书Java面试被问:Online DDL的INSTANT、INPLACE、COPY算法差异
算法