2019년 5월 25일 토요일

[leetcode] 724. Find Pivot Index

원문)
Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1.
If there are multiple pivot indexes, you should return the left-most pivot index.

번역)
정수 숫자의 배열이 주어졌을때 배열의 "pivot" 인덱스를 구하라.
"pivot"은 인덱스의 왼쪽 숫자들의 합과 인덱스의 오른쪽 숫자들의 합이 동일한 index를
뜻한다.
만약 없다면 -1을 반환.
만약 여러개라면 가장 왼쪽의 pivot 인덱스를 반환.


예제)


Example 1:
Input: 
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: 
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal 
to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

Example 2:
Input: 
nums = [1, 2, 3]
Output: -1
Explanation: 
There is no index that satisfies the conditions in the problem statement.

Note:
  • The length of nums will be in the range [0, 10000].
  • Each element nums[i] will be an integer in the range [-1000, 1000].

문제접근)
1. 접근
  • 다 되었다고 생각했는데, 느리다.
    왜 느리냐 생각해보니 sum을 계속한다 두번씩.
2. 접근

  • 왼쪽부터 더해주니까 그부분은 sum을 지웠다만 역시나 느린가 봄..
3. 접근

  • 총합을 구할 수 있다.
    그리고 접근 2의 l_sum을 가지고 있으니 r_sum도 구할 수 있다.


코드)

1. 접근

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        l = len(nums)
        
        if l == 0:
            return -1
        if 0 == sum(nums[1:]):
            return 0
        
        for i in range(1, l):
            l = nums[:i]
            r = nums[i+1:]
            if sum(l) == sum(r):
                return i
        return -1

2. 접근

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        l = len(nums)
        
        if l == 0:
            return -1
        if 0 == sum(nums[1:]):
            return 0
        
        l_sum = nums[0]
        for i in range(1, l):
            r = nums[i+1:]
            if l_sum == sum(r):
                return i
            l_sum += nums[i]
        return -1

3. 접근


class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        l = len(nums)
        t_sum = sum(nums)
        
        if l == 0:
            return -1
        if 0 == sum(nums[1:]):
            return 0
        
        l_sum = nums[0]
        for i in range(1, l):
            if l_sum == t_sum - l_sum - nums[i]:
                return i
            l_sum += nums[i]
        return -1

댓글 1개:

  1. I found that solution is very popular and helpful: https://youtu.be/brlJAIdDvkM

    답글삭제