/**
* 方案1 求最长递增子序列
* @desp 时间复杂度为O(n^2)
* @param {*} arr 目标数组
* @returns {*} 最长递增子序列长度
*/
function getLIS(arr) {
const dp = new Array(arr.length).fill(1);
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < i; j++) {
if (arr[i] > arr[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
console.log(Math.max(...dp));
return Math.max(...dp);
}
getLIS([1, 2, 3, 4, 556, 76, 8, 9]);
// ==================================
/**
* 二分查找
* @param {*} arr 辅助数组记录上次贪心结果
* @param {*} target 当前值
* @returns {*} -1 | 循环停止时,未找到target替换的是最后一项的索引
*/
function binarySearch(arr, target) {
let start = 0,
end = arr.length - 1,
mid = 0;
while (start < end) {
mid = start + Math.floor((end - start) / 2);
if (arr[mid] === target) {
return -1;
} else if (arr[mid] > target) {
end = mid - 1;
} else if (arr[mid] < target) {
start = mid + 1;
}
}
return mid;
}
/**
* 方案2 求最长递增子序列 !!!!!!!!!!!!!这个优化是错误的 部分场景能正常工作,部分场景会返回离谱的结果
* @desp 时间复杂度为O(n * logn)
* @param {*} arr 原始数组
* @returns {*} 最长递增子序列
* @returns 错误信息 |
*/
function getLIS2(arr) {
try {
const tails = [arr[0]];
for (let i = 0; i < arr.length; i++) {
const tailsLastIdx = tails.length - 1;
if (arr[i] > tails[tailsLastIdx]) {
tails.push(arr[i]);
} else if (arr[i] < tails[tailsLastIdx]) {
const index = binarySearch(tails, arr[i]);
index >= 0 && (tails[index] = arr[i]);
}
}
} catch (e) {
throw e;
}
}
getLIS2([1, 2, 3, 4, 556, 76, 8, 9]);
最长递增子序列及使用贪心和二分查找优化时间复杂度(O(n^2) => O(n * logn) )
于 2025-01-06 17:23:15 首次发布