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
- 컴퓨터과학과
- 코테
- 투포인터
- 방통대
- greedy
- dynamic programming
- LeetCode
- boj
- Binary Search
- 이진탐색
- java
- 방송대
- 탐욕알고리즘
- it
- 완전탐색
- DP
- 코딩
- two pointers
- 자바스크립트
- 깃
- 알고리즘
- Git
- algorithm
- 방송통신대학교
- 백준
- javascript
- 그리디
- 리트코드
- 자바
- sliding window
Archives
- Today
- Total
개발이 취미인 주니어 기획자
[이진탐색][JavaScript][LeetCode] #704. Binary Search 본문
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 |
🌷 내 코드

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
}

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
반응형
'문제 풀이 > 알고리즘 문제 풀이' 카테고리의 다른 글
| [투포인터][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] #35. Search Insert Position (0) | 2023.03.30 |
| [이진탐색][JavaScript][LeetCode] #278. First Bad Version (0) | 2023.03.30 |