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
相关推荐
Дерек的学习记录32 分钟前
C++:stack和queue
开发语言·c++·学习·算法
风中的微尘5 小时前
数学基础2
算法
一只小小的芙厨6 小时前
树状数组总结
数据结构·算法
郝学胜-神的一滴8 小时前
Effective STL 条款 17:用 swap 技巧去掉多余容量
c语言·开发语言·数据结构·c++·算法·rpc
玩转单片机与嵌入式8 小时前
深入浅出TinyML 36:如何验证一个TinyML系统真正具备工程应用价值?
网络·人工智能·算法
Nazarick10 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴10 小时前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴11 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_1112 小时前
算法札记:有限差分
算法
忙里偷闲学python12 小时前
GK2A 林火蔓延预报算法说明
算法