程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode solution (0330): complement the array as required (Python)

編輯:Python


subject :​ ​ The original title is link ​​( difficult )

label : Greedy Algorithm

solution

Time complexity

Spatial complexity

Execution time

Ans 1 (Python)

O ( M + l o g N )

O ( 1 )

64ms (98.65%)

Ans 2 (Python)

Ans 3 (Python)

Solution 1 :

class Solution:

def minPatches(self, nums: List[int], n: int) -> int:
# Handle the case that the array is empty
if not nums:
ans = 0
total = 0
while total < n:
total += (total + 1)
ans += 1
return ans

# When the array is not empty
else:
ans = 0

# To deal with the first 1 Before the number
total = 0
while total < nums[0] - 1:
total += (total + 1)
ans += 1

total += nums[0]
# Handle the number in the middle of the array
for i in range(1, len(nums)):
if nums[i] > n:
break
while total < nums[i] - 1:
total += (total + 1)
ans += 1
total += nums[i]

# Processing last 1 After the number
while total < n:
total += (total + 1)
ans += 1

return ans
  • 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.




  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved