Leetcode.js: Increasing Triplet Subsequence

May 21, 2018, 1 min read

Leetcode : Problem link

最直觀就是用 dp,maxIncreasing 是一個一維陣列,

maxIncreasing[i] 表示 nums[0…i] 最長的遞增子序列的長度。

那 maxIncreasing[i] = max(maxIncreasing[j] + 1),j = 0 … i。

ex:

nums          = [ 3, 5, 2, 1, 2, 3, 4]
maxIncreasing = [ 1, 2, 2, 2, 2, 3, *]

一旦發現 maxIncreasing[i] >= 3 就回傳 true。

但是麼做複雜度是 O(N2)O(N^2),實際上 leetcode 的結果也只有 9.86 %

以下是實際的 code。

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var increasingTriplet = function(nums) {
  const maxIncreasing = Array(nums.length).fill(1);

  for (let i = 1; i < nums.length; i += 1) {
    for (let j = 0; j < i; j += 1) {
      if (nums[i] > nums[j]) {
        maxIncreasing[i] = Math.max(maxIncreasing[i], maxIncreasing[j] + 1);

        if (maxIncreasing[i] >= 3) return true;
      }
    }
  }

  return false;
};

比較好的做法是宣告 a, b, c 三個變數,要找三個數字使得 a < b < c,他們就是答案。

在 i 從 0 到 nums.length 中,一旦 nums[i] 比現在 a 小, 那 nums[i] 就是最後答案的 a。

比 a 大,那他就是 b。 一旦有一個比 b 大的數,那 c 就找到了,回傳 true。

Solution:

/* beats 91.55 % */
/**
 * @param {number[]} nums
 * @return {boolean}
 */
var increasingTriplet = function(nums) {
  let a = Infinity,
      b = Infinity;

  return nums.some(c => {
    if (a >= c) a = c;
    else if (b >= c) b = c;
    else return true;
    return false;
  });
};

References

[LeetCode] Increasing Triplet Subsequence 递增的三元子序列 - 博客园

Category leetcode.js

Tags leetcode, js

Comments