SMALL

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.

 

integer 배열 nums가 주어지고, "pivot" 인덱스를 해당 배열에서 찾아라.

"pivot" 인덱스는 해당 인덱스를 기준으로 오른쪽 배열의 값들의 합과 왼쪽 배열의 값들의 합이 같은 경우를 말한다.

만약, 배열의 첫 번째 인덱스가 pivot이라면 왼쪽 배열의 합은 0이다, 왜냐하면 왼쪽에는 아무 배열도 없기 때문이다.

오른쪽도 마찬가지다.

가장 왼쪽에 위치하는 pivot 인덱스를 반환하라. 만약 존재하지 않는다면 -1을 반환하라.


우선 주어진 배열의 모든 값들을 더해서 totalSum으로 가지고 있고

하나의 포인터를 0번째 인덱스 기준으로 잡아 , 해당 포인터를 오른쪽으로 이동하며 totalSum에서 빼며 

움직인 요소들의 합과 값을 비교하는 식으로 문제를 해결해보자 ( Sliding ) 

 

    public int pivotIndex(int[] nums) {
        int totalSum = Arrays.stream(nums).sum();
        int leftSum = 0;
        int pivot = 0;

        for (int i = 0; i < nums.length; i++) {

            pivot = i;
            totalSum -= nums[i];

            if (totalSum == leftSum) {
                return pivot;
            }
            leftSum += nums[i];
        }

        return -1;
    }

하나의 포인터를 기준으로 sliding 방식으로 문제 해결 

 

 

 

 

 

LIST

+ Recent posts