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
相关推荐
丑梨数据9 分钟前
信创环境里跑文档工具:格式兼容与本地合规的几个坑
数据结构·人工智能·算法·决策树·排序算法
erzong2312 小时前
Linux操作系统:线程概念与控制
linux·算法
Nil2082 小时前
leetcode 5最长回文子串
算法·leetcode·职场和发展
xxwl5853 小时前
区域赛分类题解
c++·笔记·学习·算法
m0_674571973 小时前
力扣 hot 100 python
python·算法·leetcode
救救孩子把3 小时前
AI面试八股文-14_14-MCP-Skill-Function Calling
人工智能·安全·面试·职场和发展·推理·mcp·functioncall
青少儿编程课堂3 小时前
蓝桥杯+全国青少年信息素养大赛+电子学会PythonC/C++考级:最长公共子序列LCS解析
c++·python·算法·bfs·信息学竞赛
圣保罗的大教堂4 小时前
leetcode 3727. 最大交替平方和 中等
leetcode
倚楼听风语4 小时前
Kotlin 协程与 suspend 原理详解
java·算法·kotlin
Xin7704 小时前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode