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
相关推荐
wadesir16 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
yugi98783816 小时前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill16 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit16 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung16 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
七禾页丫17 小时前
面试记录12 中级c++开发工程师
c++·面试·职场和发展
wifi chicken17 小时前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
胡楚昊17 小时前
NSSCTF动调题包通关
开发语言·javascript·算法
Gold_Dino18 小时前
agc011_e 题解
算法
bubiyoushang88818 小时前
基于蚁群算法的直流电机PID参数整定 MATLAB 实现
数据结构·算法·matlab