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)