300. Longest Increasing Subsequence

Posted sysu_kww

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了300. Longest Increasing Subsequence相关的知识,希望对你有一定的参考价值。

 

该题是要求出字符串中最长的递增子序列的长度。第一种方法的解决思路是动态规划,定义一个与输入数组等长的整型数组,用于记录在该位置前的最长递增子序列长度。

代码如下:

 

 1 class Solution {
 2     public int lengthOfLIS(int[] nums) {
 3         
 4         if(nums.length == 0){
 5             return 0;
 6         }
 7         
 8         int[] fn = new int[nums.length];
 9         int len = 1;
10         
11         for(int i = 0 ; i < fn.length ; i++){
12             fn[i] = 1;
13         }
14         
15         
16         for(int i = 1 ; i < nums.length ; i++){
17             int maxvar = 0;
18             for(int j = 0; j < i ; j++){
19                 if(nums[i] > nums[j]){
20                     maxvar = Math.max(maxvar, fn[j]);
21                 }
22             }
23             fn[i] = maxvar + fn[i];
24             len = Math.max(len, fn[i]);
25         }
26         
27         return len;
28     }
29 }

 

还有一个就是使用二分查找的方法。

代码如下:

 

 1 class Solution {
 2     public int lengthOfLIS(int[] nums) {
 3         
 4         if(nums.length == 0){
 5             return 0;
 6         }
 7         
 8         int[] fn = new int[nums.length];
 9         int len = 0;
10         
11         for(int num : nums){
12             int i = Arrays.binarySearch(fn, 0, len, num);
13             
14             if( i < 0){
15                 i = -(i+1);
16             }
17             
18             fn[i] = num;
19             if( i == len){
20                 len++;
21             }
22         }
23         
24         return len;
25     }
26 }

 

 

END

以上是关于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