3月打卡活动第14天 LeetCode第300题:最长上升子序列(中等)

3月打卡活动第14天 LeetCode第300题:最长上升子序列(中等)

  • 题目:给定一个无序的整数数组,找到其中最长上升子序列的长度。
    在这里插入图片描述
  • 解题思路:没过,就差4个不想改了,大周末的谁还不休息呀。。。
class Solution {
    public int lengthOfLIS(int[] nums) {
        int max = 0;
        int len = nums.length;
        if(len==0) return 0;
        if(len==1) return 1;
        int now = 0;
        int left = 0;
        int right = 0;
        while(right<len){
            if(nums[left]<nums[right]){
                max++;
                now = nums[left];
                left++;
                right++;
            }else if(nums[left]>=nums[right]){
                if(nums[right]>now && now!=0){
                    now = nums[right];
                }else if(nums[right]<now){
                    now = nums[right];
                    max = 0;
                }
                left = right;
                right++;
            }
        }
        return max+1;
    }
}

在这里插入图片描述

  • 题解做法1:依次找前面比自己小的数的个数。
public class Solution {
    public int lengthOfLIS(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = 1;
        int maxans = 1;
        for (int i = 1; i < dp.length; i++) {
            int maxval = 0;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    maxval = Math.max(maxval, dp[j]);
                }
            }
            dp[i] = maxval + 1;
            maxans = Math.max(maxans, dp[i]);
        }
        return maxans;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/zui-chang-shang-sheng-zi-xu-lie-by-leetcode-soluti/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

发布了100 篇原创文章 · 获赞 12 · 访问量 2354

猜你喜欢

转载自blog.csdn.net/new_whiter/article/details/104856247