Skip to content

Latest commit

 

History

History
87 lines (49 loc) · 1.53 KB

File metadata and controls

87 lines (49 loc) · 1.53 KB

中文文档

Description

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. 

Note:

    <li>There may be more than one LIS combination, it is only necessary for you to return the length.</li>
    
    <li>Your algorithm should run in O(<i>n<sup>2</sup></i>) complexity.</li>
    

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

Solutions

Python3

Java

class Solution {
    public int lengthOfLIS(int[] nums) {
        int n = nums.length;
        if (n < 2) {
            return n;
        }
        int[] dp = new int[n];
        dp[0] = 1;
        int res = 1;
        for (int i = 1; i < n; ++i) {
            int maxVal = 0;
            for (int j = 0; j < i; ++j) {
                if (nums[j] < nums[i]) {
                    maxVal = Math.max(maxVal, dp[j]);
                }
            }
            dp[i] = maxVal + 1;
            res = Math.max(res, dp[i]);
        }
        return res;

    }
}

...