前文
继上篇Leetcode题medium73/74/75/78/79/80/81/90/105/106,Python多种解法(五),继续分享ARRAY剩余的medium题,下篇开始string的题目分享。
120. Triangle
class Solution(object):
"""
用dp的思路来完成,因为triangle里的层次,每个位置相当于被上面的两个节点所共有,但从上到下的dp会导致元素变多,
所以从下到上来实现,如下;
minpath[k][i] = min( minpath[k+1][i], minpath[k+1][i+1]) + triangle[k][i];
因为minpath[k][i]只使用一次,所以可以变成一维dp:
minpath[i] = min( minpath[i], minpath[i+1]) + triangle[k][i];
Runtime: 20 ms, faster than 100.00% of Python online submissions for Triangle.
Memory Usage: 11 MB, less than 97.17% of Python online submissions for Triangle.
"""
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
n = len(triangle)
dp = triangle[-1]
for i in range(n - 2, -1, -1):
for j in range(len(triangle[i])):
dp[j] = min(dp[j+1], dp[j]) + triangle[i][j]
return dp[0]
152. Maximum Product Subarray
class Solution(object):
"""
这解法是真的牛逼,or 1是当列表里遇到0的时候,就乘以1,这样就能跳过0的存在
同时需要计算翻转过来的另一个列表集合和,比如[-1,1,1],如果是正向计算的话就是
[-1,-1,-1],反向计算就是:[1,1,-1],所以需要反向计算
Runtime: 24 ms, faster than 98.70% of Python online submissions for Maximum Product Subarray.
Memory Usage: 12 MB, less than 17.74% of Python online submissions for Maximum Product Subarray.
"""
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
rev_nums = nums[::-1]
for i in range(1, len(nums)):
nums[i] *= nums[i-1] or 1
rev_nums[i] *= rev_nums[i-1] or 1
return max(nums+rev_nums)
153. Find Minimum in Rotated Sorted Array
class MySolution(object):
"""
观察发现遍历时下一个数小于上一个数就说明是最小值,因此代码直接遍历即可得到;如果没有找到,则直接返回第一个
Runtime: 16 ms, faster than 100.00% of Python online submissions for Find Minimum in Rotated Sorted Array.
Memory Usage: 10.9 MB, less than 45.22% of Python online submissions for Find Minimum in Rotated Sorted Array.
"""
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return False
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
return nums[i+1]
return nums[0]
class Solution(object):
"""
讨论区。。
Runtime: 16 ms, faster than 100.00% of Python online submissions for Find Minimum in Rotated Sorted Array.
Memory Usage: 11.1 MB, less than 5.65% of Python online submissions for Find Minimum in Rotated Sorted Array.
"""
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return min(nums)
class Solution2(object):
"""
二分法才是终极奥义
Runtime: 16 ms, faster than 100.00% of Python online submissions for Find Minimum in Rotated Sorted Array.
Memory Usage: 10.9 MB, less than 43.04% of Python online submissions for Find Minimum in Rotated Sorted Array.
"""
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo, hi = 0, len(nums)-1
while lo <= hi:
mid = lo + (hi-lo)//2
if nums[mid] > nums[hi]:
lo = mid+1
elif mid == 0 or (mid-1 >= 0 and nums[mid-1] > nums[mid]):
return nums[mid]
else:
hi = mid-1
raise RuntimeError
162. Find Peak Element
class Solution(object):
"""
同153,利用二分法的思想
Runtime: 16 ms, faster than 100.00% of Python online submissions for Find Peak Element.
Memory Usage: 10.9 MB, less than 25.95% of Python online submissions for Find Peak Element.
"""
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo = 0
hi = len(nums) - 1
while lo < hi:
mid = lo + (hi-lo)//2
if nums[mid] > nums[mid+1]:
hi = mid
else:
lo = mid + 1
return lo
209. Minimum Size Subarray Sum
class Solution2(object):
"""
定义快慢指针,当快指针达到所在的位置>=s时,进行判断,将这个值减去慢指针,取满足条件的最小值ans,然后不断迭代该过程,
Runtime: 28 ms, faster than 86.79% of Python online submissions for Minimum Size Subarray Sum.
Memory Usage: 11.9 MB, less than 51.61% of Python online submissions for Minimum Size Subarray Sum.
"""
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
ans = n = len(nums)
l = r = sr = 0
while r < n:
sr += nums[r]
r += 1
if sr >= s:
while sr - nums[l] >= s:
sr -= nums[l]
l += 1
ans = min(ans, r - l)
return ans if sr >= s else 0
216. Combination Sum III
class Solution(object):
"""
dfs递归来完成
Runtime: 20 ms, faster than 86.08% of Python online submissions for Combination Sum III.
Memory Usage: 10.7 MB, less than 76.06% of Python online submissions for Combination Sum III.
"""
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
res = []
self.dfs(range(1,10),k,n,0,[],res)
return res
def dfs(self,nums,k,n,index,path,res):
if k < 0 or n < 0:
return
if k == 0 and n == 0:
res.append(path)
for i in range(index, len(nums)):
self.dfs(nums,k-1,n-nums[i],i+1,path+[nums[i]],res)
228. Summary Ranges
class Solution(object):
"""
[]+[]=[],直接根据题目搞个集合,比如是[0,1,2,4,5,7],则for循环后集合为[[0,2],[4,5],[7]]
代码里的range[-1][1:] = n,直接把列表里处于端点内的数字直接去除了,最后一步通过join拼接即可
Runtime: 16 ms, faster than 100.00% of Python online submissions for Summary Ranges.
Memory Usage: 10.7 MB, less than 55.79% of Python online submissions for Summary Ranges.
"""
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
ranges = []
for n in nums:
if not ranges or n > ranges[-1][-1] + 1:
ranges += [],
ranges[-1][1:] = n,
return ['->'.join(map(str, r)) for r in ranges]
class Solution2(object):
"""
同上解法,不过用两列表,同时利用列表是可变序列来进行编辑
Runtime: 16 ms, faster than 100.00% of Python online submissions for Summary Ranges.
Memory Usage: 10.8 MB, less than 32.63% of Python online submissions for Summary Ranges.
"""
def summaryRanges(self, nums):
"""
:type nums: List[int]
:rtype: List[str]
"""
ranges, r = [], []
for n in nums:
if n-1 not in r:
r = []
ranges += r,
r[1:] = n,
return ['->'.join(map(str, r)) for r in ranges]
229. Majority Element II
class Solution(object):
"""
直接利用set、len、列表的count、等等python的内置函数结构来完成
Runtime: 40 ms, faster than 23.57% of Python online submissions for Majority Element II.
Memory Usage: 11.6 MB, less than 21.25% of Python online submissions for Majority Element II.
"""
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return [num for num in set(nums) if nums.count(num) > len(nums)/3]
238. Product of Array Except Self
class Solution(object):
"""
Runtime: 96 ms, faster than 70.90% of Python online submissions for Product of Array Except Self.
Memory Usage: 18.7 MB, less than 28.32% of Python online submissions for Product of Array Except Self.
"""
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
re = list()
re.append(1)
temp = 1
for i in range(0,len(nums)-1):
temp = temp * nums[i]
re.append(temp)
temp = 1
for i in range(len(nums)-2,-1,-1):
temp = temp * nums[i+1]
re[i] = re[i] * temp
return re
总结
此次分享到此结束~