[LeetCode] Find Pivot Index
https://leetcode.com/problems/find-pivot-index/?envType=study-plan-v2&envId=leetcode-75
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
Constraints:
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
숫자로 이루어진 배열 nums가 주어진다.
어떤 인덱스를 기점으로 좌우 숫자들의 합이 동일할 때 그 인덱스를 pivot index라고 한다.
단, 좌 우 숫자들의 합을 구할 때 pivot index 위치의 숫자는 제외하고 더해야 한다.
이 pivot index를 구하고, 그런 인덱스가 없는 경우 -1을 리턴하면 된다.
const pivotIndex = function(nums) {
for(let i=0; i<nums.length; i++){
const leftSide = sumAll(nums.slice(0,i));
const rightSide = sumAll(nums.slice(i+1, nums.length));
if(leftSide == rightSide){
return i;
}
}
return -1;
};
const sumAll = (arr) =>{
return arr.reduce((a, b) => a + b, 0);
}
처음에는 일단 배열을 index기준으로 자른 다음에 양 옆을 더하고 그게 같으면 i를 리턴하도록 했다.
이렇게 하니까 통과는 됐는데 영 효율이 안나오는 코드가 되었음.
당연하다. 배열의 길이가 길어질수록 합을 구하는 것도 반복될테니까..
reduce도 결국 반복문이니..지금 보니 통과가 된 게 신기하네ㅋㅋㅋ
const pivotIndex = function(nums) {
let leftSide = 0;
let rightSide = sumAll(nums) - nums[0];
let result = 0;
for(let i=0; i<nums.length; i++){
if(leftSide == rightSide){
return i;
}
leftSide += nums[i];
rightSide -= nums[i+1]
}
return -1;
};
const sumAll = (arr) =>{
return arr.reduce((a, b) => a + b, 0);
}
아무튼 이미 더해놨던 값들을 다시 활용하는 식으로 코드를 바꿨더니 바로 효율이 확 높아졌다~.~
'코테연습' 카테고리의 다른 글
[LeetCode] Find the Difference of Two Arrays (0) | 2025.04.23 |
---|---|
[LeetCode] Find the Highest Altitude (0) | 2025.04.21 |
[LeetCode] Longest Subarray of 1's After Deleting One Element (2) | 2025.04.17 |