[LeetCode] 724. Find Pivot Index

Semidragon·2023년 11월 8일
0

CodingTest

목록 보기
17/80

1. Question

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
 

2. Thoughts

3. Tips learned

4. My solution

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        right_sum = sum(nums) - nums[0]
        left_sum = 0
        for i in range(len(nums) - 1):
            if right_sum == left_sum:
                return i
            right_sum -= nums[i + 1]
            left_sum += nums[i]

        if left_sum == 0:
            return len(nums) - 1
        else:
            return -1

746/746 cases passed (137 ms)
Your runtime beats 66.66 % of python3 submissions
Your memory usage beats 44.71 % of python3 submissions (17.5 MB)

5. AI Solution and Improvements

Here's a refined version of your code:

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        total_sum = sum(nums)
        left_sum = 0
        for i, num in enumerate(nums):
            if left_sum == (total_sum - left_sum - num):
                return i
            left_sum += num
        return -1

In this version:

  • We use enumerate to get both the index and the value in the array, which is a common Pythonic practice.
  • We check the pivot condition inside the loop. If the current left sum equals the total sum minus the current left sum and the current number, then we've found the pivot index.
  • The final check outside the loop is not necessary because if the pivot index is at the last position, it would be returned inside the loop.

This code will return the leftmost pivot index if it exists, or -1 if it doesn't, as per the problem statement.

profile
Semidragon's network [CS undergrad @ Sungkyunkwan University | Networks + System @ CSI]

0개의 댓글