leetcode_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?

思路:

理论上来讲,从每一个元素开始向前遍历,用一个数max来统计到目前为止,前面比当前元素小的有多少个,当max小于当前元素遍历的值时,更新max,最后max的值就是最大递增子序列的长度,问题得解,简单易懂,时间复杂度O(n*n),空间复杂度O(n)。毫无疑问上述方法是可行的,但时间效率不高。但怎么去降低运算的数量呢?可行的方法是有的,就是在前面统计的基础上用数组记录每个元素对应的递增子序列的长度,统计每个元素的次数时,从后向前统计,在出现更大的max时统计终止,否则统计到元素初始的位置,可以减少一部分运算量。至于题目所说的O(nlogn)复杂度的方法,还没有想到。

代码:

public int lengthOfLIS(int[] nums) {
        if(nums==null||nums.length==0)
            return 0;
        int countArr[]=new int[nums.length];
        int max=1,i=0,j=0;
        Arrays.fill(countArr,1);
        for(i=1;i=0;j--)
            {
                if(nums[i]>nums[j]&&countArr[j]+1>countArr[i])
                {
                    countArr[i]=countArr[j]+1;
                    if(countArr[i]>max)
                    {
                        max=countArr[i];
                        break;
                    }
                        
                }
            }
        }
        return max;
    }


你可能感兴趣的:(leetcode)