LeetCode-300.Longst Increasing Subsequence
Posted 月半榨菜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-300.Longst 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 is4
.
Note:
- There may be more than one LIS combination, it is only necessary for you to return the length.
- Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
使用dp,时间复杂度为O(n2)
1 public int lengthOfLIS(int[] nums) {//dp my 2 if(null==nums||0==nums.length){ 3 return 0; 4 } 5 int max= 1; 6 int[] re = new int[nums.length];//存放当前位置的最大长度 7 re[0]=1; 8 for(int i=1;i<nums.length;i++){ 9 re[i]=0; 10 for(int j=i-1;j>=0;j--){ 11 if(nums[j]<nums[i]&&re[i]<re[j]){//从当前位置往前,第一个比nums[i]小的值 12 re[i] = re[j]; 13 } 14 } 15 re[i]++; 16 if(re[i]>max){ 17 max =re[i]; 18 } 19 } 20 return max; 21 }
利用二分,时间复杂度为O(nlogn)
public int lengthOfLIS(int[] nums) {//二分 mytip if(null==nums||0==nums.length){ return 0; } List<Integer> re = new ArrayList<>();// re.add(nums[0]); int index = 0; for(int i=1;i<nums.length;i++){ if(nums[i]>re.get(re.size()-1)){//如果大于最后一个元素,直接插入 re.add(nums[i]); } else{ index = bs(0,re.size()-1,re,nums[i]);//二分找到第一个不大于nusm[i]的数的下标,然后替换为当前数 re.set(index,nums[i]); } } return re.size();//数组长度为最大值 } private int bs(int left,int right,List<Integer> list,int num){ while(left<=right){ if(left >= right){ return left; } else{ int mid = left + (right - left)/2; if(list.get(mid)<num){ left = mid+1; } else{ right =mid; } } } return left; }
以上是关于LeetCode-300.Longst Increasing Subsequence的主要内容,如果未能解决你的问题,请参考以下文章