卖萌的弱渣

I am stupid, I am hungry.

Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

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?

Solution

(Longest-Increasing-Subsequence.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution(object):
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # n^2: 
        # dp[i]: the longest increasing subsequence
        dp = [1]*len(nums)
        for i in range(len(nums)):
            for j in range(i):
                if nums[i] > nums[j] and dp[i] < dp[j]+1:
                    dp[i] = dp[j] + 1
        rt = 0
        for i in range(len(nums)):
            if rt < dp[i]:
                rt = dp[i]
        return rt

        # n(logn)
        # dp: is an array to record the longest increasing subsequence
        dp = []
        for i in range(len(nums)):
            start = 0
            end = len(dp)-1
            # binary search dp, find the place dp[mid] < nums[i]
            while start <= end:
                mid = (start+end)/2
                if dp[mid] >= nums[i]:
                    end = mid - 1
                else:
                    start = mid + 1
            if start >= len(dp):
                dp.append(nums[i])
            else:
                dp[start] = nums[i]
        return len(dp)