forked from someshgkale123/LeetCode-Easy
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Find Pivot Index
75 lines (65 loc) · 2.04 KB
/
Find Pivot Index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Problem Statement:
Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to
the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
Example 1:
Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
Example 2:
Input: nums = [1,2,3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Solution:
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
"""
start=0
end=0
for i in range(len(nums)):
start=sum(nums[:i])
end=sum(nums[i+1:])
if start==end:
return i
return -1
"""
"""
if len(nums)==1:
return 0
if len(nums)==0:
return -1
leftsum=[nums[0]]
for each in range(1,len(nums)):
leftsum.append(leftsum[-1]+nums[each])
rightsum=[nums[-1]]
for each in range(len(nums)-2,-1,-1):
rightsum.append(rightsum[-1]+nums[each])
rightsum=rightsum[::-1]
left=-1
right=1
for i in range(len(nums)):
l,r=0,0
if left>=0:
l=leftsum[left]
if right<len(rightsum):
r=rightsum[right]
if l==r:
return i
left+=1
right+=1
return -1
"""
if len(nums)==1:
return 0
leftsm=0
rightsm=sum(nums)
for each in range(len(nums)):
rightsm-=nums[each]
if leftsm==rightsm:
return each
leftsm+=nums[each]
return -1