[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 };