leetcode学习笔记58

300. Longest Increasing Subsequence

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.
1、二分查找法

class Solution {
    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        int len = 0;
        for (int num : nums) {
            int i = Arrays.binarySearch(dp, 0, len, num);
            if (i < 0) {
                i = -(i + 1);
            }
            dp[i] = num;
            if (i == len) {
                len++;
            }
        }
        return len;
    }
}

2、动态分配

class Solution {
    public int lengthOfLIS(int[] nums) {
        if(nums.length==0)return 0;
        int[] res=new int[nums.length];
        int max=1;
        res[0]=1;
        for(int i=1;i<nums.length;i++){
            int curr=helper(nums,i,res);
            if(max<curr){
                max=curr;
            }
        }
        return max;
    }
    public int helper(int[] nums,int i,int[] res) {
        int max=1;
        for(int j=0;j<i;j++){
            int curr=1;
            if(nums[j]<nums[i]){
                curr=res[j]+1;
                if(curr>max){
                    max=curr;
                }
            }         
        }
        res[i]=max;
        return res[i]; 
    }
}

你可能感兴趣的:(leetcode)