Leetcode 724. Find Pivot Index

发布时间:2024年01月03日

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

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
文章来源:https://blog.csdn.net/mobius_strip/article/details/135371301
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。