300. Longest Increasing Subsequence
来源:互联网 发布:怎么投诉淘宝买家骚扰 编辑:程序博客网 时间:2024/06/01 09:50
the normal way:
public class Solution { public int lengthOfLIS(int[] nums) { if(nums == null || nums.length == 0) return 0; int[] dp = new int[nums.length]; Arrays.fill(dp,1); int ret = 1; for(int i = 1; i<nums.length; i++){ int max = 1; for(int j = 0; j<i;j++){ if(nums[i]>nums[j]){ max = Math.max(dp[j]+1, max); } } dp[i] = max; ret = Math.max(ret,max); } return ret; }}
dp[i] means the LIS from nums[0] to nums[i]. when nums[i+1] comes in, we just need to check dp[0] -> dp[i], find the max dp[k] where nums[k] < nums[i+1]
then dp[i+1] = dp[k] + 1.
the O(nlgn) way:
public class Solution { public int lengthOfLIS(int[] nums) { int[] dp = new int[nums.length]; Arrays.fill(dp,Integer.MAX_VALUE); for(int i : nums){ int index = binarySearch(dp,i); if(index < 0){ dp[-(index + 1)] = i; } } for(int i = dp.length - 1; i>=0; i--){ if(dp[i] != Integer.MAX_VALUE){ return i+1; } } return 0; } int binarySearch(int[] nums, int i){ int start = 0; int end = nums.length; while(start<end){ int midIndex = start + (end - start)/2; int mid = nums[midIndex]; if(mid < i){ start = midIndex + 1; } else if(mid == i){ return midIndex; } else{ end = midIndex; } } return -start - 1; }}
we could maintain an array of the current LIS while i increase, when a new element nums[i] comes, we should replace first element larger then nums[i]. if no element larger than nums[i], we just append it to the last of the LIS.
for example,
1,3,4,2,0,6,3
1
1,3
1,3,4
1,2,4
0,2,4
0,2,4,6
0,2,3,6
Anyway the longest index ever reached in the dp array will be the length of LIS. the substitution ensures the current LIS is always optimal.
PS, we could use the built-in Arrays.binarySearch to achieve the same result.
0 0
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- 300. Longest Increasing Subsequence
- Nginx+Apache搭建动静分离
- Windows Qt 解析网络数据出现ssl错误
- Deeplearning4j 实战(1):Deeplearning4j 手写体数字识别
- 高并发系统之降级特技
- c#获取异常对象最内层的报错信息
- 300. Longest Increasing Subsequence
- js基于像素查找DOM元素的方法
- java map hashmap linkedhashmap hashtable treemap
- Java异常抛出及自定义异常
- 让你的 JMeter 像 LoadRunner 那样实时查看每秒事务数(TPS)、事务响应时间(TRT)
- Ubuntu下搜狗输入法的种种问题
- RecyclerView嵌套GridView显示不全,Item的复用的问题
- VB最简单的程序自毁
- akka学习教程(十) agent