서하아빠의 개발 블로그

724. Find Pivot Index 본문

알고리즘/LeetCode

724. Find Pivot Index

서하아빠 2023. 6. 17. 21:25

문제

풀이방법

pivot 인덱스를 기준으로 왼쪽과 오른쪽의 합의 같을 때의 pivot 인덱스를 반환하는 문제

전체 합을 먼저 구해놓고 앞에서 부터 빼서 왼쪽 합, 오른쪽 합을 비교해서 

  1. 왼쪽 합과 오른쪽 합이 동일 : 해당 index를 반환
  2. 왼쪽 합과 오른쪽 합이 다름 : for문을 계속 순환 
var pivotIndex = function(nums) {
    let total = nums.reduce((a,b) => a+b)
    let leftSum = 0;
    for (let i = 0; i < nums.length; i++) {
        const rightSum = total - leftSum - nums[i];
        if (leftSum === rightSum) return i;
        leftSum += nums[i];
    }
    return -1;
};

 

'알고리즘 > LeetCode' 카테고리의 다른 글

1832. Check if the Sentence Is Pangram  (0) 2023.12.10
867. Transpose Matrix  (0) 2023.07.07
20. Valid Parentheses  (0) 2022.05.24
121. Best Time to Buy and Sell Stock  (0) 2022.05.20
217. Contains Duplicate  (0) 2022.05.20