[leetcode] Pivot Index

수민·2023년 2월 17일
0

프론트엔드

목록 보기
48/48

문제

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.

-> 번역

정수 배열이 주어지면 이 배열의 피벗 인덱스를nums 계산합니다 .

피벗 인덱스는 인덱스 왼쪽에 있는 모든 숫자의 합이 인덱스 오른쪽에 있는 모든 숫자의 합계와 같은 인덱스 입니다 .

인덱스가 배열의 왼쪽 가장자리에 있으면 왼쪽 0에 요소가 없기 때문에 왼쪽 합이 됩니다. 이는 배열의 오른쪽 가장자리에도 적용됩니다.

가장 왼쪽 피벗 인덱스를 반환 합니다 . 해당 색인이 없으면 를 반환합니다 -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

설명:

먼저 예제를 살펴보고 그 이면의 논리를 이해해 봅시다.

예제에 따르면 숫자 배열이 있습니다.

인덱스와 함께 시각화하면 다음과 같은 결과를 얻습니다.

이제 이미지를 보면 왼쪽에 3개 요소, 오른쪽에 2개 요소를 추가하면 11. 따라서 그 사이의 요소에는 피벗 인덱스 가 될 인덱스가 있습니다 .
따라서 우리의 경우
Array[3] = 63은 피벗 인덱스입니다.

논리:
이제 피벗 인덱스를 확인하는 방법에 대한 문제를 살펴보겠습니다.

먼저 배열에 있는 모든 요소의 합을 알고 이를 로 표시해야 합니다 totalSum. 여기서는 28입니다.

그런 다음 왼쪽 인덱스의 모든 요소의 합계를 구하고 다음과 같이 표시합니다.leftSum

이제 이러한 요소로 테이블을 만들고 우리가 가지고 있는 인덱스의 요소를 추적하고 그것을 표시하고 Index[e]그것이 무엇과 같은지 확인할 수 있습니다.

문제를 오른쪽에서 왼쪽으로 접근해 봅시다.

우리는 leftSum아무것도 추가하지 않았기 때문에 현재 0입니다. 그리고 Index[e]해당 인덱스에 있는 배열의 요소입니다.

leftSum배열의 각 항목에 대해 이 작업을 수행하면 가 에 있는 동일한 숫자와 같은 하나의 조건이 됩니다 leftSum. 해당 조건 뒤의 다음 인덱스는 pivot Index.

그리고 우리의 문제는 피벗 인덱스를 찾는 것입니다.

totalSum- leftSum- Index[e]=leftSum

나의코드


let pivotIndex=function(nums){
 
  let totalSum=0, leftSum=0;


  nums.forEach((el)=>{
    totalSum+=el;
  })

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

    leftSum+=nums[i];
  }

  return -1;
}


console.log(pivotIndex([1,7,3,6,5,6]));
console.log(pivotIndex([1,2,3]));
console.log(pivotIndex([2,1,-1]));
profile
헬창목표

0개의 댓글