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
相关推荐
NEFU_Jyj1 小时前
牛客周赛R168
算法
文丑颜不良啊8 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z9 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH9 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶10 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊10 小时前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊11 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
文丑颜不良啊12 小时前
LeetCode2141~2160题目解析
java·leetcode
LabVIEW开发12 小时前
LabVIEW 连接板:28 个端子怎么排,优先级怎么定
java·算法·labview