개발이 취미인 주니어 기획자

[이진탐색][JavaScript][LeetCode] #704. Binary Search 본문

문제 풀이/알고리즘 문제 풀이

[이진탐색][JavaScript][LeetCode] #704. Binary Search

큐 2023. 3. 29. 13:30
728x90
반응형

#이진탐색  #EASY

 

Binary Search - LeetCode

Can you solve this real interview question? Binary Search - Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

leetcode.com

 

🌷 문제 설명

✏️ LeetCode 704. Binary Search
Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
You must write an algorithm with O(log n) runtime complexity.

🎃 제한 사항
1 <= nums.length <= 10^4
-1^4 < nums[i], target < 10^4
All the integers in nums are unique.
nums is sorted in ascending order.

입출력 예

nums target Output
[-1, 0, 3, 5, 9, 12] 9 4
[-1, 0, 3, 5, 9, 12] 2 -1

 

🌷 내 코드

index변수를 새로 만들어 넣어줬을 때

var search = function(nums, target) {
    let start = 0
    let end = nums.length-1
    let index = 0

    while (end >= start) {
        let mid = Math.floor((start+end)/2)
        if (target === nums[mid]) {
            index = mid
            return index
        } else if (target > nums[mid]) {
            start = mid+1
            index = start+1
        } else {
            end = mid-1
            index = end+1
        }
    }
    return -1
}

 

index변수 없이 그냥 mid를 바로 리턴

var search = function(nums, target) {
    let start = 0
    let end = nums.length-1

    while (end >= start) {
        let mid = Math.floor((start+end)/2)
        if (target === nums[mid]) {
            return mid
        } else if (target > nums[mid]) {
            start = mid+1
        } else {
            end = mid-1
        }
    }
    return -1
}

var search = function(nums, target) {
    return nums.indexOf(target)
};

이건 이진탐색 생각안하고 첨에 풀었던 코드...ㅎ 

 

🌷 코멘트

index 저거 하나 할당했다고 왜 빨라지는거지?
JavaScript와 TypeScript 코드 진짜 형식만 선언해준거 외에는 다 똑같은데(결론적으로 타입스크립트 코드가 더 긴데도 불구하고) 메모리 차이 많이 나는게 신기

 


블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!

~대가리 꽃밭인 디지털 노마드가 꿈이예요~

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

noob. qminlee723 has 8 repositories available. Follow their code on GitHub.

github.com

728x90
반응형