-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leetcode-300.js
38 lines (37 loc) · 921 Bytes
/
Leetcode-300.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 300. Longest Increasing Subsequence
* https://leetcode-cn.com/problems/longest-increasing-subsequence/
* @param {number[]} nums
* @return {number}
*/
/**
* DP 数组 O(n^2)
const lengthOfLIS = (nums) => {
if (!nums.length) return 0
let dp = new Array(nums.length).fill(1)
for (let i = 1; i < nums.length; i++) {
for (let j = 0; j < i; j++) {
if (nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1)
}
}
return Math.max(...dp)
}
*/
/**
* DP + 二分查找 O(nlogn)
*/
const lengthOfLIS = (nums) => {
if (nums.length <= 1) return nums.length
let tail = new Array(nums.length), result = 0
for (let i = 0; i < nums.length; i++) {
let left = 0, right = result
while (left < right) {
let mid = (left + right) >> 1
if (tail[mid] < nums[i]) left = mid + 1
else right = mid
}
tail[left] = nums[i]
result == right && result++
}
return result
}