Leetcode Problem number # 724: Find Pivot Index problem and solution

preview_player
Показать описание
Leetcode Problem number 724: Find Pivot Index problem and solution

Problem:

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.

If no such index exists, return -1.

Example:
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

Solution:

To solve this problem, we can first calculate the sum of all elements in the array. Then, we can iterate through the array and keep track of the left sum and right sum separately.

If the left sum is equal to the right sum, then we have found the pivot index. If we reach the end of the array without finding the pivot index, then it does not exist, so we return -1.

Here's the code:

class LeetCode_724:
def pivotIndex(self, nums: List[int]) :
n = len(nums)
sum = 0
leftSum = 0
for i in range(n):
sum += nums[i]
for i in range(n):
if (leftSum == sum - leftSum - nums[i]):
return i
leftSum += nums[i]
return -1

In the first loop, we calculate the sum of all elements in the array. In the second loop, we iterate through the array and keep track of the left sum and right sum. If the left sum is equal to the right sum, we return the current index. If we reach the end of the array without finding the pivot index, we return -1.
Рекомендации по теме
visit shbcf.ru