Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
1.动态规划:核心思想是使用一个数组dp来保存,dp[i]的意义是到该位置为止的最长递增子序列。
最后求所有位置的最大值,而不是dp的最后元素。
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp=[0]*len(nums)
dp[0]=1
for i in range(1,len(nums)):
tmax=1
for j in range(0,i):
if nums[i]>nums[j]:
tmax=max(tmax,dp[j]+1)
dp[i]=tmax
return max(dp)
2.二分查找
用动态规划的复杂度是 O(n^2)
Follow up: Could you improve it to O(n log n) time complexity?
先建立一个LIS数组,把首元素放进去,然后依次比较后面的元素,如果遍历到的新元素比LIS数组的首元素小的话,替换首元素;如果遍历到的新元素比LIS数组的首元素大的话,将新元素添加至LIS数组末尾;如果遍历到的新元素比LIS数组首元素大,比尾元素小时,此时用二分查找法找到第一个不小于此新元素的位置,覆盖掉位置的原来的数字。以此类推直至遍历完整个 nums 数组,此时 LIS数组的长度就是我们要求的长度,特别注意的是 LIS数组的值可能不是一个真实的LIS,比如若输入数组nums为 {4, 2, 4, 5, 3, 7},那么算完后的ends数组为{2, 3, 5, 7},可以发现它不是一个原数组的LIS,只是长度相等而已。
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
LIS = [nums[0]]
for i in range(1, len(nums)):
if nums[i] < LIS[0]:
LIS[0] = nums[i]
elif nums[i] > LIS[-1]:
LIS.append(nums[i])
else:
low, high = 0, len(LIS)
while low < high:
mid = (low + high)//2
if nums[i] > LIS[mid]: low = mid + 1
else: high = mid
LIS[high] = nums[i]
return len(LIS)
3.在别人那里看到的思路:跟上面那种方法很类似,思路是先建立一个空的dp数组,然后开始遍历原数组,对于每一个遍历到的数字,我们用二分查找法在dp数组找第一个不小于它的数字,如果这个数字不存在,那么直接在dp数组后面加上遍历到的数字,如果存在,则将这个数字更新为当前遍历到的数字,最后返回dp数字的长度即可,注意的是,跟上面的方法一样,特别注意的是dp数组的值可能不是一个真实的LIS。参见代码如下:
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [nums[0]]
for i in range(1, len(nums)):
low, high = 0, len(dp)
while low < high:
mid = (low + high)//2
if nums[i] > dp[mid]:
low = mid + 1
else:
high = mid
if high == len(dp):
dp.append(nums[i])
else:
dp[high]=nums[i]
return len(dp)