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

LeetCode 704 - Binary Search (Easy)

by HandHand 2023. 5. 14.

 

πŸ’‘ 문제

LeetCode - 704번

 

🎯 풀이 κ³Όμ •

μ •λ ¬λœ λ°°μ—΄μ—μ„œ νŠΉμ • target 의 index λ₯Ό λ°˜ν™˜ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

이뢄 탐색 을 μ΄μš©ν•˜λ©΄ μ‰½κ²Œ ν•΄κ²°ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

 

πŸ‘¨‍πŸ’» μ½”λ“œ

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var search = function(nums, target) {
    let head = 0
    let tail = nums.length - 1
    let answer = -1

    while (head <= tail) {
        const mid = Math.floor((head + tail) / 2)

        if (nums[mid] < target) {
            head = mid + 1
        } else if (nums[mid] > target) {
            tail = mid - 1
        } else {
            answer = mid
            break
        }
    }

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

πŸ’¬ λŒ“κΈ€