LeetCode-- rise longest sequence (LIS)

A disorder of a given integer array, the length of the longest found rising sequence.
Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4
explained: the longest sequence is increased [2,3,7,101], its length is 4.
Description:

Various combinations may be increased up sequence, you only need to output a corresponding length.
The time complexity of your algorithm should be O (n2).

Recursion

int[] f = new int[10000];
    int[] p = new int[10000];

    public int robot(int idx, int[] nums) {

        if (idx < 0) {
            return 0;
        }

        if (f[idx] > 0) {
            return f[idx];
        }

        int ans = 0;
        for(int i = 0; i < idx; i++) {
            if (nums[idx] > nums[i]) {
                ans = Math.max(ans, robot(i, nums));
            }
        }
        f[idx] = ans + 1;
        return ans + 1;
    }

    public int lengthOfLIS(int[] nums) {
        for(int i = 0; i < nums.length; i++) {
            p[i] = nums[i];
        }
        int n = nums.length;
        p[n] = 1000000;
        return robot(n, p) - 1;
    }

Non-recursive



非递归

public int lengthOfLIS_1(int[] nums) {

    for(int i = 0; i < nums.length; i++) {
        p[i] = nums[i];
    }
    int n = nums.length;
    p[n] = 1000000;
    n++;
    for(int idx = 0; idx < n; idx++) {
        int ans = 0;
        for(int i = 0; i < idx; i++) {
            if (p[idx] > p[i]) {
                ans = Math.max(ans, f[i]);
            }
        }
        f[idx] = ans + 1;
    }
    return f[n - 1] - 1;
}
```
时间复杂度为O(nlogn)

public int lengthOfLIS_2(int[] nums) {

    for(int i = 0; i < nums.length; i++) {
        p[i] = nums[i];
    }
    int n = nums.length;
    p[n] = 1000000;
    n++;

    int[] min = new int[10000];
    for(int i = 0; i < min.length; i++) {
        min[i] = 100000001;
    }
    int path = 0;

    for(int idx = 0; idx < n; idx++) {
        int ans = 0;
        int L = 0, R = path;
        while(L <= R) {
            int mid = (L + R) / 2;
            if (p[idx] > min[mid]) {
                ans = mid;
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        f[idx] = ans + 1;
        min[f[idx]] = Math.min(min[f[idx]], p[idx]);
        path = Math.max(path, f[idx]);
    }
    return f[n - 1] - 1;
}

“`

Guess you like

Origin blog.csdn.net/reuxfhc/article/details/80897257