8000 330, either expand by x or by max_reach + 1 · xzlin/LeetCode_Python_Accepted@2777226 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2777226

Browse files
committed
330, either expand by x or by max_reach + 1
1 parent dc4b4b0 commit 2777226

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

330_Patching_Array.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,15 @@
1-
# 2015-01-26 149 tests, 48 ms
1+
# 2016-03-16, 149 tests, 44 ms
22
class Solution(object):
33
def minPatches(self, nums, n):
44
"""
55
:type nums: List[int]
66
:type n: int
77
:rtype: int
88
"""
9-
i, patchCount, maxReach, numLength = 0, 0, 1, len(nums)
10-
while maxReach <= n:
11-
if i < numLength and nums[i] <= maxReach:
12-
maxReach += nums[i]
13-
i += 1
14-
else:
15-
maxReach <<= 1
16-
patchCount += 1 # add maxReach into nums
17-
return patchCount
9+
patch_count, max_reach = 0, 0 # we can form any number in [1, max_reach]
10+
for x in nums + [float('inf')]:
11+
while max_reach + 1 < x and max_reach < n:
12+
# the patch we add is max_reach + 1
13+
patch_count, max_reach = patch_count + 1, max_reach + max_reach + 1
14+
if max_reach >= n: return patch_count
15+
max_reach += x

0 commit comments

Comments
 (0)
0