LeetCode 300. 最长上升子序列

Posted by cody1991 on August 5, 2020

简单思路:还可以优化

300. 最长上升子序列

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
/**
 * @param {number[]} nums
 * @return {number}
 */
var lengthOfLIS = function (nums) {
  if (!nums || nums.length === 0) return 0;
  if (nums.length === 1) return 1;
  const list = [];
  list.push(nums[0]);

  for (let index = 1; index < nums.length; index += 1) {
    const cur = nums[index];
    const last = list[list.length - 1];

    if (cur > last) {
      list.push(cur);
    } else {
      let findIndex = list.length - 1;

      while (list[findIndex] >= cur) {
        findIndex--;
      }

      list.splice(findIndex + 1, 1, cur);
    }

    console.log(list);
  }

  return list.length;
};

console.log(lengthOfLIS([2, 2]));