01 最長上升子序列
給定一個無序的整數數組,找到其中最長上升子序列的長度。
示例:
輸入: [10,9,2,5,3,7,101,18]
輸出: 4
解釋: 最長的上升子序列是 [2,3,7,101],它的長度是 4。
說明:
- 可能會有多種最長上升子序列的組合,你只需要輸出對應的長度即可。
- 你算法的時間複雜度應該爲 O(n2) 。
- 進階: 你能將算法的時間複雜度降低到 O(n log n) 嗎?
解法1
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
ans = 1
foo = [1 for _ in range(len(nums))]
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
foo[i] = max(foo[i],foo[j]+1)
ans = max(ans,foo[i])
print(foo)
return ans
解法2
from bisect import bisect_left
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
foo = []
for num in nums:
index = bisect_left(foo, num)
if len(foo) == index:
foo.append(num)
else:
foo[index] = num
return len(foo)
02 俄羅斯套娃信封問題
給定一些標記了寬度和高度的信封,寬度和高度以整數對形式 (w, h) 出現。當另一個信封的寬度和高度都比這個信封大的時候,這個信封就可以放進另一個信封裏,如同俄羅斯套娃一樣。
請計算最多能有多少個信封能組成一組“俄羅斯套娃”信封(即可以把一個信封放到另一個信封裏面)。
說明:
- 不允許旋轉信封。
示例:
輸入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
輸出: 3
解釋: 最多信封的個數爲 3, 組合爲: [2,3] => [5,4] => [6,7]。
解法:
from bisect import bisect_left
class Solution(object):
def maxEnvelopes(self, envelopes):
"""
:type envelopes: List[List[int]]
:rtype: int
"""
envelopes = sorted(envelopes, key = lambda it: [it[0],-it[1]])
lenn = len(envelopes)
if lenn == 0 or lenn == 1:
return lenn
foo = []
for _,h in envelopes:
index = bisect_left(foo, h)
if len(foo) == index:
foo.append(h)
else:
foo[index] = h
print(foo)
return len(foo)