Leetcode: Longest Increasing Subsequence

Question

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(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.

Hide Tags Dynamic Programming Binary Search

Solution 1

time complexity: O( n2 )

class Solution(object):
    def lengthOfLIS(self, nums):
        """ :type nums: List[int] :rtype: int """

        res = 0
        if nums==[]:
            return res

        dp = [1]*len(nums)

        for ind in range(1,len(nums)):
            for j in range(ind):
                if nums[j]<=nums[ind] and dp[j]+1>dp[ind]:
                    dp[ind] = dp[j] + 1
            res = max( res, dp[ind] )

        return res

It will cause “Exceed Time Limit”

Solution 2

Time complexity: O(nlogn)

class Solution(object):
    def lengthOfLIS(self, nums):
        """ :type nums: List[int] :rtype: int """

        res = 0 
        if nums==[]:
            return res

        temp = []
        temp.append(nums[0])
        res = 1

        for ind in range(1,len(nums)):
            left, right = 0, res-1
            while left<=right:
                #print 'left,right: ', left , right
                mid = (left+right)/2
                #print temp,mid, ind
                if temp[mid]<nums[ind]:
                    left = mid + 1
                else:
                    right = mid - 1

            #print 'after binary search: ', left
            if left<len(temp):
                temp[left] = nums[ind]
            else:
                temp.append(nums[ind])

            if left>=res:
                res += 1

        return res

你可能感兴趣的:(Leetcode: Longest Increasing Subsequence)