λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 240 - Search a 2D Matrix II (Medium)

by HandHand 2021. 3. 2.

문제

LeetCode - 155번

풀이 κ³Όμ •

이차원 λ°°μ—΄μ—μ„œ λͺ©ν‘œκ°’이 μ‘΄μž¬ν•˜λŠ”μ§€ νŒλ‹¨ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

κ·Έλƒ₯ 브루트 포슀 둜 μ ‘κ·Όν•œλ‹€λ©΄ O(MN) 의 μ‹œκ°„ λ³΅μž‘λ„λ‘œ ν•΄κ²°ν• μˆ˜λ„ μžˆμ§€λ§Œ
μ’€ 더 효율적인 탐색을 μœ„ν•΄ 이뢄 탐색 을 μ μš©ν–ˆμŠ΅λ‹ˆλ‹€.

각 행이 μ˜€λ¦„μ°¨μˆœμœΌλ‘œ μ •λ ¬λ˜μ–΄ μžˆλ‹€λŠ” 점을 μ΄μš©ν•΄μ„œ 각 ν–‰λ§ˆλ‹€ 이뢄 탐색 을 μˆ˜ν–‰ν•΄ μ›ν•˜λŠ” 값이 μ‘΄μž¬ν•˜λŠ”μ§€ νŒλ‹¨ν•©λ‹ˆλ‹€.

μ½”λ“œ

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function (matrix, target) {
  for (let row of matrix) {
    if (bisect(row, target)) return true;
  }

  return false;
};

function bisect(arr, target) {
  let lo = 0;
  let hi = arr.length - 1;

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

    if (arr[mid] === target) return true;
    else if (arr[mid] > target) hi = mid - 1;
    else lo = mid + 1;
  }

  return false;
}
λ°˜μ‘ν˜•

'πŸƒ algorithm > leetcode' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

LeetCode 46 - Permutations (Medium)  (0) 2021.03.03
LeetCode 21 - Merge Two Sorted Lists (Easy)  (0) 2021.03.02
LeetCode 155 - Min Stack (Easy)  (0) 2021.03.02
LeetCode 39 - Combination Sum (Medium)  (0) 2021.03.02
LeetCode 20 - Valid Parentheses (Easy)  (0) 2021.03.02

πŸ’¬ λŒ“κΈ€