[LeetCode][JavaScript]Longest Increasing Subsequence

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?

https://leetcode.com/problems/longest-increasing-subsequence/

 

 

 


 

 

动态规划。

先是O(n2)的解法,dp[i]是以nums[i]结尾的最长子串的长度。

 

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var lengthOfLIS = function(nums) {
 6     var max = 0, dp = [], i, j, curMax;
 7     for(i = 0; i < nums.length; i++){
 8         curMax = 0;
 9         for(j = 0; j < i; j++){
10             if(nums[i] > nums[j] && dp[j] > curMax){
11                 curMax = dp[j];
12             }
13         }
14         curMax++;
15         if(curMax > max){
16             max = curMax;
17         }
18         dp[i] = curMax;
19     }
20     return max;
21 };

 

O(logn)的解法,dp[i]是以dp[i]结尾的长度为i的子串。

比如[1,5,4,6]

1. dp = [1]

2. dp = [1,5],长度为2的子串最小以5结尾

3. dp = [1,4],长度为2的子串最小以4结尾

4. dp = [1,4,6],长度为3的子串最小以6结尾

结果就是dp的长度3。

 

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var lengthOfLIS = function(nums) {
 6     var dp = [], i, j, len;
 7     for(i = 0; i < nums.length; i++){
 8         len = dp.length;
 9         if(len === 0 || dp[len - 1] < nums[i]){
10             dp[len] = nums[i];
11         }else{
12             dp[bSearch(nums[i], 0, len - 1)] = nums[i];
13         }
14         
15     }
16     return dp.length;
17     
18     function bSearch(num, i, j){
19         if(i === j){
20             return i;
21         }
22         var middle = parseInt((i + j) / 2);
23         if(dp[middle] < num){
24             return bSearch(num, middle + 1, j);
25         }
26         return bSearch(num, i, middle);
27     }
28 };

 

 

转载于:https://www.cnblogs.com/Liok3187/p/4967239.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值