【Leetcode】Longest Increasing Subsequence

题目链接:https://leetcode.com/problems/longest-increasing-subsequence/

题目:

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that 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?

思路:

1、简单动态规划,c[i]表示从0~i的数组中 包含nums[i]的LIS,状态转移方程:c[i]=max{c[j]+1} ,j<i且nums[i]>nums[j],时间复杂度为O(n^2)

2、动态规划加二分搜索,b[i]表示长度为i的LIS最后一个元素大小,end是b数组最后一个元素也就是当前LIS的下标。  对每个元素进行如下判断:

若nums[i]>b[end],则更新LIS,否则二分搜索b数组比nums[i]元素大的最小位置idx,此时b[idx]>nums[i]>b[idx-1] 更新idx位置,因为此时同样长度的子串,包含nums[i]的要比包含b[idx]要小。  时间复杂度O(nlogn)。

算法

1、

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public int lengthOfLIS(int[] nums) {  
  2.     if (nums.length == 0)  
  3.         return 0;  
  4.     int c[] = new int[nums.length];// c[i]表示从0~i 以nums[i]结尾的最长增长子串的长度  
  5.     c[0] = 1;  
  6.     int maxLength = 1;  
  7.   
  8.     for (int i = 1; i < nums.length; i++) {  
  9.         int tmp = 1;  
  10.         for (int j = 0; j < i; j++) {  
  11.             if (nums[i] > nums[j]) {  
  12.                 tmp = Math.max(c[j] + 1, tmp);  
  13.             }  
  14.         }  
  15.         c[i] = tmp;  
  16.         maxLength = Math.max(maxLength, c[i]);  
  17.     }  
  18.   
  19.     return maxLength;  
  20. }  


2、

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public int lengthOfLIS(int[] nums) {  
  2.     if (nums.length == 0)  
  3.         return 0;  
  4.   
  5.     int b[] = new int[nums.length + 1];// 长度为i的子串 最后一个数最小值  
  6.     int end = 1;  
  7.     b[end] = nums[0];  
  8.   
  9.     for (int i = 1; i < nums.length; i++) {  
  10.         if (nums[i] > b[end]) {// 比最长子串最后元素还大,则更新最长子串长度  
  11.             end++;  
  12.             b[end] = nums[i];  
  13.         } else {// 否则更新b数组  
  14.             int idx = binarySearch(b, nums[i], end);  
  15.             b[idx] = nums[i];  
  16.         }  
  17.     }  
  18.     return end;  
  19. }  
  20.   
  21. /** 
  22.  * 二分查找大于t的最小值,并返回其位置 
  23.  */  
  24. public int binarySearch(int[] b, int target, int end) {  
  25.     int low = 1, high = end;  
  26.     while (low <= high) {  
  27.         int mid = (low + high) / 2;  
  28.         if (target > b[mid])  
  29.             low = mid + 1;  
  30.         else  
  31.             high = mid - 1;  
  32.     }  
  33.     return low;  
  34. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值