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

[이진탐색][JavaScript][LeetCode] #35. Search Insert Position 본문

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

[이진탐색][JavaScript][LeetCode] #35. Search Insert Position

큐 2023. 3. 30. 12:00
728x90
반응형

#이진탐색  #EASY

 

Search Insert Position - LeetCode

Can you solve this real interview question? Search Insert Position - Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must w

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: Search Insert Position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.

🎃 제한 사항
1 <= nums.length <= 10^4
-10^4 <= nums[i] <= 10^4
nums contains distinct values sorted in ascending order.
-10^4 <= target <= 10^4

입출력 예

nums target result
[1, 3, 5, 6] 5 2
[1, 3, 5, 6] 2 1
[1, 3, 5, 6]
7 4

 

🌷 내 코드

1. 반복구문 활용 코드

자바스크립트
타입스크립트. 메모리는 지맘대로라 모르겠고~ 일단 런타임은 느림

var searchInsert = function(nums, target) {
    let start = 0
    let end = nums.length-1
    while (end >= start) {
        let mid = Math.floor((start+end)/2)
        if (nums[mid] === target) {
            return mid
        } else if (nums[mid] < target) {
            start = mid+1
        } else {
            end = mid-1
        }
    }
    return start
};

2. 재귀 활용 코드

var searchInsert = function(nums, target) {

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

    return recursion(nums, target, 0, nums.length)
};

 

🌷 코멘트

오 한 번에 성공. 신난당
메모리 차지는 조금 더 하긴 했지만 여기도 재귀가 더 빠름. 신기하군

 


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

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

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

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

github.com

728x90
반응형