상세 컨텐츠

본문 제목

724. Find Pivot Index

LeetCode

by 10002s 2023. 11. 11. 17:51

본문

Find Pivot Index - LeetCode

 

정수 배열 nums가 주어졌을 때, 이 배열의 피벗 인덱스를 계산하세요.
피벗 인덱스는 해당 인덱스를 기준으로 왼쪽의 모든 숫자의 합이 오른쪽의 모든 숫자의 합과 동일한 인덱스를 나타냅니다.
만약 인덱스가 배열의 왼쪽 끝에 있다면, 왼쪽의 합은 0이 됩니다. 이는 배열의 오른쪽 끝에도 적용됩니다.
가장 왼쪽에 있는 피벗 인덱스를 반환하세요. 만약 이러한 인덱스가 없다면 -1을 반환하세요.

 

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

Example 2:

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

Example 3:

Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0
문제 요약:

정수 배열 nums가 주어지고, 피벗 인덱스를 찾아야 합니다. 피벗 인덱스는 해당 인덱스를 기준으로 왼쪽의 합과 오른쪽의 합이 동일한 지점을 나타냅니다. 만약 그런 인덱스가 없다면 -1을 반환합니다.

풀이과정 설명:
  1. 배열의 총 합을 계산합니다.
  2. 왼쪽 합을 나타낼 변수 leftSum을 초기화합니다.
  3. 배열을 순회하면서 현재 인덱스를 기준으로 왼쪽 합과 오른쪽 합을 비교합니다.
  4. 피벗 인덱스를 찾으면 해당 인덱스를 반환합니다. 없다면 -1을 반환합니다.
class Solution {
    public int pivotIndex(int[] nums) {
        int totalSum = 0;
        int leftSum = 0;

        for (int num : nums) {
            totalSum += num;
        }

        for (int i = 0; i < nums.length; i++) {
            if (leftSum == totalSum - leftSum - nums[i]) {
                return i;
            }
            leftSum += nums[i];
        }

        return -1;
    }
}

 

풀이과정 설명:
  1. 좌측 배열 0 기준으로 좌/우의 총합을 구한다.
  2. 배열을 순회하면서 다음 인덱스 값을 더하고/빼주고~ 계산하고~
  3. 배열을 순회하면서 현재 인덱스를 기준으로 왼쪽 합과 오른쪽 합을 비교합니다.
  4. 피벗 인덱스를 찾으면 해당 인덱스를 반환합니다. 없다면 -1을 반환합니다.
class Solution {
    public int pivotIndex(int[] nums) {
        int sumLeft =  0;
        int sumRight = -nums[0];

        for(int num : nums){
            sumRight += num;
        }

        for(int i = 0; i < nums.length; i++){
            if(sumLeft == sumRight) return i;

            sumLeft += nums[i];
            if(i + 1 < nums.length){
                sumRight -= nums[i+1];
            }
        }

        return -1;
    }
}
반응형

관련글 더보기