LeetCode:Longest Increasing Subsequence

Longest Increasing Subsequence


 
Total Accepted: 29178  Total Submissions: 84440  Difficulty: Medium

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

Hide Similar Problems
  (M) Increasing Triplet Subsequence

n^2解法:

动规典型算法:LIS(最长增长子序列),时间复杂度n^2。

c++ code:

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len = nums.size();
        int dp[len];
        
        for(int i=0;i<len;i++) {
            int tmax = 1;
            for(int j=0;j<i;j++) {
                if(nums[j] < nums[i]) {
                    tmax = tmax > dp[j]+1 ? tmax : dp[j]+1;
                }
            }
            dp[i] = tmax;
        }
        
        int ans = 0;
        for(int i=0;i<len;i++) {
            ans = dp[i] > ans ? dp[i] : ans;
        }
        
        return ans;
    }
};

nlogn解法:

动规 + 二分查找,时间复杂度nlogn。

分析:

示例:nums = 9,2,3,7,8,4,5,6
    num=9 -> dp=9
    num=2 -> dp=2
    num=3 -> dp=2,3
    num=7 -> dp=2,3,7
    num=8 -> dp=2,3,7,8
    num=4 -> dp=2,3,4,8
    num=5 -> dp=2,3,4,5
    num=6 -> dp=2,3,4,5,6

java code:

public class Solution {
    public int lengthOfLIS(int[] nums) {
        
        int[] dp = new int[nums.length];
        
        int lenLIS = 0;
        for(int num:nums) {
            int index = Arrays.binarySearch(dp,0,lenLIS,num);
            if(index < 0) // index < 0,表示无此元素,index = -(insertion point) - 1。具体可查看binarySearch API
                index = -(index + 1);
            dp[index] = num;
            
            if(lenLIS == index) lenLIS++; // 此时的num是dp中最大值
        }
        
        return lenLIS;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值