Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
Tags
- 투포인터
- 자바
- 그리디
- 깃
- DP
- 컴퓨터과학과
- boj
- 방통대
- javascript
- LeetCode
- 이진탐색
- two pointers
- algorithm
- it
- 백준
- java
- greedy
- 방송대
- 탐욕알고리즘
- 방송통신대학교
- 코테
- 코딩
- Git
- 리트코드
- Binary Search
- 완전탐색
- 알고리즘
- 자바스크립트
- dynamic programming
- sliding window
Archives
- Today
- Total
개발이 취미인 주니어 기획자
[이진탐색][JavaScript][LeetCode] #35. Search Insert Position 본문
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
반응형
'문제 풀이 > 알고리즘 문제 풀이' 카테고리의 다른 글
| [투포인터][JavaScript][LeetCode] #344. Reverse String (0) | 2023.04.01 |
|---|---|
| [투포인터][JavaScript][LeetCode] #283. Move Zeros (0) | 2023.03.31 |
| [투포인터][JavaScript][LeetCode] #977. Squares of a Sorted Array (0) | 2023.03.30 |
| [이진탐색][JavaScript][LeetCode] #278. First Bad Version (0) | 2023.03.30 |
| [이진탐색][JavaScript][LeetCode] #704. Binary Search (0) | 2023.03.29 |