300. Longest Increasing Subsequence

来源:互联网 发布:cajviewer mac版 编辑:程序博客网 时间:2024/05/29 10:23

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.

Subscribe to see which companies asked this question

动规?

public class Solution {    public int lengthOfLIS(int[] nums) {        int ret = 0  ;        if(nums.length==0)return 0;        if(nums.length==1)return 1;        int [] shadow = new int [nums.length];        for(int i = nums.length-1;i>=0;--i){            shadow[i]=1;            for(int j = i+1;j<nums.length;j++){                if(nums[j]>nums[i]){                    shadow[i]=shadow[j]+1;                                       break;                }            }            int j=i+1;            for(;j<nums.length;j++){                if(shadow[j]<shadow[i]){                    break;                }            }                                for(int k = i;k<j-1;k++){                    int temp1 = shadow[k];                    int temp2 = nums[k];                    shadow[k]=shadow[k+1];                    nums[k]=nums[k+1];                    shadow[k+1]=temp1;                    nums[k+1]=temp2;                    }             if(shadow[i]>ret)ret = shadow[i];        }        return ret;    }}

0 0
原创粉丝点击