2021. 11. 3. 00:29ㆍLeetcode
Description 724:
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.
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).
Description 1991:
A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].
If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.
Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Example 724:
Example 1991:
'''
[1] brute force)
code::
def findMiddleIndex(self, nums: List[int]) -> int:
for i in range(len(nums)):
left_sum,right_sum=0,0
for j in range(i):
left_sum+=nums[j]
for k in range(i+1,len(nums)):
right_sum+=nums[k]
if left_sum==right_sum:
return i
return -1
-T/C: O(n^2)
-S/C: O(1)
'''
'''
[2] using prefix and suffix array)
code::
def findMiddleIndex(self, nums: List[int]) -> int:
prefix=[nums[0] for _ in range(len(nums))]
suffix=[nums[-1] for _ in range(len(nums))]
for i in range(1,len(nums)):
prefix[i]=prefix[i-1]+nums[i]
for i in range(len(nums)-2,-1,-1):
suffix[i]=suffix[i+1]+nums[i]
for i in range(len(nums)):
if prefix[i]==suffix[i]:
return i
return -1
-T/C: O(n)
-S/C: O(n)
'''
'''
[3] using prefix and suffix sum)
code::
def findMiddleIndex(self, nums: List[int]) -> int:
left_sum=0
right_sum=0
for num in nums:
right_sum+=num
for i in range(len(nums)):
right_sum-=nums[i]
if left_sum==right_sum:
return i
left_sum+=nums[i]
return -1
-T/C: O(n)
-S/C: O(1)
'''
class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
left_sum=0
right_sum=0
for num in nums:
right_sum+=num
for i in range(len(nums)):
right_sum-=nums[i]
if left_sum==right_sum:
return i
left_sum+=nums[i]
return -1
'Leetcode' 카테고리의 다른 글
48. Rotate Image (0) | 2021.11.03 |
---|---|
54. Spiral Matrix (0) | 2021.11.03 |
79. Word Search (0) | 2021.11.02 |
152. Maximum Product Subarray (0) | 2021.11.02 |
34. Find First and Last Position of Element in Sorted Array (0) | 2021.10.30 |