[leetcode][python3] 724번 - Find Pivot Index

numango·2024년 9월 11일

leetcode

목록 보기
6/12

문제
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.

Example 1:

Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11


특정 요소의 왼쪽 배열의 합과 오른쪽 배열의 합이 같을때 그 요소의 인덱스를 반환해야 한다.

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        self.nums = nums
        leftSum = 0
        rightSum = sum(nums) 
        for i in range(len(nums)):
            if(leftSum == rightSum - nums[i]):
                return i
            else:
                rightSum -= nums[i]
                leftSum += nums[i]

        return -1

0개의 댓글