文章目录
- 1 题目理解
- 2 动态规划
- 3 二分+贪心
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;}
}