프로그램 개발/미분류

[LeetCode/Python/Java]Array and String - Find Pivot Index

(ㅇㅅㅎ) 2020. 8. 21. 15:47
728x90
반응형

 

문제

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 all the numbers to the left of the index is equal to the sum of all 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.

 

해석해보면 배열 안에 한 인덱스 기준으로 왼쪽 값들의 합과 오른쪽 값들의 합이 같은 인덱스를 찾는 것입니다. 만약 인덱스 값이 없을 경우는 -1을 리턴합니다.

 

예를 들어 배열 A가 [1, 7, 3, 6, 5, 6] 일 때 1 + 7 + 3 = 5 + 6 이므로 3번째 인덱스를 리턴하는 것이고 배열 B가 [1, 2, 3] 일 때는 -1을 리턴하는 것입니다.

 

코드를 보시려면 더보기를 클릭해 주세요.

더보기

파이썬 코드

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

 

자바 코드

자바 코드는 Solution에 있는 풀이 부분을 가져온 것입니다.

class Solution {
    public int pivotIndex(int[] nums) {
        int sum = 0, leftsum = 0;
        for (int x: nums) sum += x;
        for (int i = 0; i < nums.length++i) {
            if (leftsum == sum - leftsum - nums[i]) return i;
            leftsum += nums[i];
        }
        return -1;
    }
}
 
반응형