300. Longest Increasing Subsequence

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?


public class Solution {
    public int lengthOfLIS(int[] nums) {
        int []f = new int[nums.length];
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            f[i] = 1; //至少有自己一个递增子序列
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i] && f[i] <= f[j] + 1) {  //保证只比最大的大1个,前面乱序的不会乱加
                    f[i] = f[j] + 1;
                }
            }
            if (f[i] > max) {
                max = f[i];
            }
        }
        return max;
    }
}



Nums 1,3,5,2,8,4,6
Lis:  1,2,3,2,4,3

当做到第6位时,当j指针走到nums为2的时候lis[i]并不用更新,这是因为此时的lis[i]已经是4了,并没有小于等于lis[j]

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