Skip to content

Latest commit

 

History

History
52 lines (38 loc) · 1.83 KB

풀이_LC724.md

File metadata and controls

52 lines (38 loc) · 1.83 KB

👻 724. Find Pivot Index

  • Date : 2021.10.31(일)
  • Time : 30분

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.

Constraints

  • 1 <= nums.length <= 10^4
  • -1000 <= nums[i] <= 1000

Example

  • 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
    



풀이

    def pivotIndex(self, nums: List[int]) -> int:
        right_sums = {}
        current_sum = 0

        for i in range(len(nums) - 1, -1, -1):
            right_sums[i] = current_sum
            current_sum += nums[i]

        current_sum = 0
        for i in range(len(nums)):
            if current_sum == right_sums[i]:
                return i
            current_sum += nums[i]

        return -1
    
        

: 피벗 인덱스는 인덱스의 왼쪽에 있는 모든 숫자의 합이 인덱스의 오른쪽에 있는 모든 숫자의 합과 같은 인덱스를 말한다. 그래서 처음 for문을 통해 {5: 0, 4: 6, 3: 11, 2: 17, 1: 20, 0: 27} 이런 dict을 구현해주었다. 이 뜻은 0번째 인덱스까지 제외하고 합은 27, 1번째 인덱스까지 제외하면 합은 20 이런 뜻이다. 이렇게 구성을 다 만들어두었다면 두번째 for 문을 통해 오른쪽 합(피벗)이 왼쪽 인덱스값의 합과 같은지 검사해주면 된다.