https://leetcode.com/problems/find-pivot-index/description
Find Pivot Index - LeetCode
Can you solve this real interview question? Find Pivot Index - 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
leetcode.com
Q. 특정 index를 기준으로, 우측과 좌측의 합이 같다면, 이 index를 피봇 index라 한다. 이 피봇 index를 찾아라.
Solution.
보통 알고리즘 문제 풀이는 TC를 O(N)가 되도록 풀면, 대체로 옳은 답인 경우가 많다. 여기세 in-place로 풀라고 한다거나 그런 식이다.
이 문제도 추가 버퍼를 사용하여 미리 합을 저장해 놓으면 이를 이용해서 쉽게 해결이 가능하다.
int pivotIndex(vector<int>& nums)
{
vector<int> leftSum, rightSum;
for (int k = 0; k < nums.size(); ++k)
{
if (leftSum.size() == 0) leftSum.push_back(0);
else leftSum.push_back(leftSum[leftSum.size() - 1] + nums[k - 1]);
int r = nums.size() - 1 - k;
if (rightSum.size() == 0) rightSum.push_back(0);
else rightSum.push_back(rightSum[rightSum.size() - 1] + nums[r + 1]);
}
for (int k = 0; k < nums.size(); ++k)
{
if (leftSum[k] == rightSum[nums.size()-1-k])
return k;
}
return -1;
}
'Leetcode > LeetCode75' 카테고리의 다른 글
[HashMap/Set][Easy] 1207. Unique Number of Occurrences (0) | 2023.12.09 |
---|---|
[HashMap/Set][Easy] 2215. Find the Difference of Two Arrays (0) | 2023.12.09 |
[PrefixSum][Easy] 1732. Find the Highest Altitude (1) | 2023.12.07 |
[Sliding Window][Medium] 1493. Longest Subarray of 1's After Deleting One Element (1) | 2023.12.05 |
[Sliding Window][Medium] 1004. Max Consecutive Ones III (2) | 2023.12.05 |