Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n^2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
题意:
给一个无序的整数数组,找到最长的升序子序列的长度
例如:[10, 9, 2, 5, 3, 7, 101, 18], 最长的升序子序列为 [2, 3, 7, 101]
思考:
是否可以写出时间复杂度为 O(n log n) 的算法
参考:
http://bookshadow.com/weblog/2015/11/03/leetcode-longest-increasing-subsequence/
思路:
动态规划:O(n^2)
每个数字 x 找到它前面比它小的数字 的个数
状态转移方程为:
dp[x]=max(dp[x],dp[y]+1)
Python
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==[]:
return 0
l=len(nums)
dp=[1]*l
for x in range(l):
for y in range(x):
if nums[x]>nums[y]:
dp[x]=max(dp[x],dp[y]+1)
return max(dp)
思路:
二分法
ans用来存储最终的升序子序列
初始时ans[0]=nums[0],逐个向后比较nums[x],用二分法,确定nums[x]在ans中的位置:
如果比当前ans的最大值还要大,则加在ans后面
如果开始比某个值小了,则把它放在这个值的位置上
Python
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
size=len(nums)
ans=[]
for x in range(size):
low=0
high=len(ans)-1
while low<=high:
mid=(low+high)/2
if ans[mid]<nums[x]: #目的就是把下一个大的元素放在相应的位置:如果比最后一个大,就append到最后
low=mid+1 #如果不是比最后一个大,就找到那个位置low,把low替换成这个值
else:
high=mid-1 #如果ans[mid]>nums[x], 则用 high<low 去控制,然后把low上的值代替
if low>=len(ans): #初始时ans[0]=nums[0],逐个向后比较,遇到大的,则加在ans后面
ans.append(nums[x])
else: #遇到小的,则把它放在最小,因为是要升序的子序列
ans[low]=nums[x]
return len(ans)
Input:
[10,9,2,5,3,7,101,18]
Output:
[2,3,7,18]