๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 300 - Longest Increasing Subsequence (Medium)

by HandHand 2021. 6. 14.

๋ฌธ์ œ

LeetCode - 300๋ฒˆ

ํ’€์ด ๊ณผ์ •

๊ฐ€์žฅ ๊ธด ๋ถ€๋ถ„์ˆ˜์—ด์„ ๊ตฌํ•˜๋Š” LIS ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋™์  ๊ณ„ํš๋ฒ• ์„ ์ด์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜๋„ ์žˆ์ง€๋งŒ ์ด๋ถ„ ํƒ์ƒ‰ ์„ ์ด์šฉํ•˜๋ฉด Nlog(N) ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


/**
 * @param {number[]} nums
 * @return {number}
 */
var lengthOfLIS = function (nums) {
  const memo = [];

  for (const num of nums) {
    if (memo.length === 0) {
      memo.push(num);
      continue;
    }

    if (memo.length > 0 && memo[memo.length - 1] < num) {
      memo.push(num);
    } else {
      const idx = binarySearch(memo, num);
      memo[idx] = num;
    }
  }

  return memo.length;
};

function binarySearch(arr, target) {
  let lo = 0,
    hi = arr.length - 1;
  let idx = 2e9;

  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);

    if (arr[mid] < target) {
      lo = mid + 1;
    } else {
      idx = Math.min(idx, mid);
      hi = mid - 1;
    }
  }

  return idx;
}
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 733 - Flood Fill (Easy)  (0) 2022.03.07
LeetCode 229 - Majority Element II (Medium)  (0) 2022.02.22
LeetCode 36 - Valid Sudoku (Medium)  (0) 2021.04.13
LeetCode 120 - Triangle (Medium)  (0) 2021.04.13
LeetCode 38 - Count and Say (Medium)  (0) 2021.04.13

๐Ÿ’ฌ ๋Œ“๊ธ€