LeetCode 300. Longest Increasing Subsequence

分析

难度 中
来源 https://leetcode.com/problems/longest-increasing-subsequence/
思路
tails is an array storing the smallest tail of all increasing subsequences with length i+1 in tails[i].
For example, say we have nums = [4,5,6,3], then all the available increasing subsequences are:

len = 1 : [4], [5], [6], [3] => tails[0] = 3
len = 2 : [4, 5], [5, 6] => tails[1] = 5
len = 3 : [4, 5, 6] => tails[2] = 6

We can easily prove that tails is a increasing array. Therefore it is possible to do a binary search in tails array to find the one needs update.

Each time we only do one of the two:

(1) if x is larger than all tails, append it, increase the size by 1
(2) if tails[i-1] < x <= tails[i], update tails[i]

题目

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:
• 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?

解答

Runtime: 0 ms, faster than 100.00% of Java online submissions for Longest Increasing Subsequence.
Memory Usage: 34.3 MB, less than 89.04% of Java online submissions for Longest Increasing Subsequence.

package LeetCode;

public class L300_LongestIncresingSubsequence {
    public int lengthOfLIS(int[] nums) {
        if(nums.length<1)
            return 0;
        int[] tails=new int[nums.length+1];
        tails[0]=nums[0];
        int len=1;

        for(int i=1;i<nums.length;i++)
        {
            if(nums[i]<tails[0])
                tails[0]=nums[i];
            if(nums[i]>tails[len-1]){
                tails[++len-1]=nums[i];
            }else{
                for(int j=0;j<len-1;j++){
                    if(nums[i]>tails[j]&&nums[i]<tails[j+1]){
                        tails[j+1]=nums[i];
                    }
                }
            }
            /*for(int j=0;j<len;j++){
                System.out.print(tails[j]+"\t");
            }
            System.out.println();*/
        }
        return len;
    }
    public static void main(String[] args){
        L300_LongestIncresingSubsequence l300=new L300_LongestIncresingSubsequence();
        int[] nums={10,9,2,5,3,7,101,18};
        System.out.println(l300.lengthOfLIS(nums));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值