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 Tags
  Dynamic Programming Binary Search
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。

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;
    }
}


你可能感兴趣的:(LeetCode,longest,S,Increasing)