Skip to content

Commit 31e8af9

Browse files
committed
feat: add Binary Search
1 parent 00c9da0 commit 31e8af9

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,4 @@ https://neetcode.io/roadmap
2727
| 739 | [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) | Medium | [TypeScript](./TypeScript/739.daily-temperatures.ts) | Stack |
2828
| 853 | [Car Fleet](https://leetcode.com/problems/car-fleet/) | Medium | [TypeScript](./TypeScript/853.car-fleet.ts) | Stack |
2929
| 84 | [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | Hard | [TypeScript](./TypeScript/84.largest-rectangle-in-histogram.ts) | Stack |
30+
| 704 | [Binary Search](https://leetcode.com/problems/binary-search/) | Easy | [TypeScript](./TypeScript/704.binary-search.ts) | Binary Search |

TypeScript/704.binary-search.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function search(nums: number[], target: number): number {
2+
let low = 0;
3+
let high = nums.length;
4+
5+
while (low <= high) {
6+
let mid = Math.floor((low + high) / 2);
7+
8+
if (nums[mid] === target) {
9+
return mid;
10+
} else if (nums[mid] > target) {
11+
high = mid - 1;
12+
} else {
13+
low = mid + 1;
14+
}
15+
}
16+
17+
return -1;
18+
}

0 commit comments

Comments
 (0)