300. Longest Increasing Subsequence

1 题目理解

Given an integer array nums, return the length of the longest strictly increasing subsequence.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

输入:整数数组int[] nums
输出:最长递增子序列长度
规则:子序列是指从原数组中找出若干元素组成新的数组。这些元素不一定是下标相邻的,但是元素前后顺序不能变。递增子序列就是新的子数组中,i>j,a[i]>=a[j]。
Example 1:
Input: nums = [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.

2 动态规划

动态规划解法参考文章

3 二分+贪心

这道题目可以用二分来解释,我现在还是很惊讶。文章思路来源于力扣官方

要是上升子序列越长,那上升子序列应该尽可能上升得慢一些。
我们可以用一个数组tail,tail[i]表示长度为i的子序列的最小末尾元素。用len记录子序列长度。
我们注意到关于tail[i]是一个关于i单调递增的函数。
例如nums={0,8,4,12,2}。
初始化的时候tail[1]= 0。
遇到8的时候,因为nums[i]>tail[1],所以直接追加在tail后面,tail={0,8}。
遇到4的时候,需要在tail数组中找到最小的比4大的元素下标,并且替换。也就是需要替换8 ,形成tail={0,4}。
遇到12的时候,因为nums[i]>tail[2],所以直接追加在tail后面,tail={0,4,12}。
遇到2的时候,需要在tail数组中找到最小的比2大的元素下标,并且替换。也就是需要替换84,形成tail={0,2,12}。

class Solution {
    public int lengthOfLIS(int[] nums) {
        int n = nums.length;
        int[] tail = new int[n+1];
        int res = 0;
        int len = 1;
        tail[len] = nums[0];
        for(int i=1;i<n;i++){
            if(nums[i]>tail[len]){
                len++;
                tail[len] = nums[i];
            }else{
                int left = 1,right=len;
                //在数组中找到最大的left使得tail[left]<nums[i]
                while(left<=right){
                    int m  = left + ((right-left)>>1);
                    if(tail[m]>=nums[i]){
                        right = m-1;
                    }else{
                        left = m+1;
                    }
                }
                tail[left] = nums[i];
            }
        }
        return len;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值