码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Longest Increasing Subsequence

时间:2016-05-22 12:23:17      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

题目链接: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
 技术分享技术分享
  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
 技术分享技术分享
  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. }  

【Leetcode】Longest Increasing Subsequence

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51472702

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!