Skip to content

Commit 55ede8b

Browse files
committed
Add solution #704
1 parent 7d257e8 commit 55ede8b

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@
125125
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|
126126
700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy|
127127
701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium|
128+
704|[Binary Search](./0704-binary-search.js)|Easy|
128129
713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium|
129130
722|[Remove Comments](./0722-remove-comments.js)|Medium|
130131
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|

Diff for: solutions/0704-binary-search.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* 704. Binary Search
3+
* https://leetcode.com/problems/binary-search/
4+
* Difficulty: Easy
5+
*
6+
* Given an array of integers nums which is sorted in ascending order, and an
7+
* integer target, write a function to search target in nums. If target exists,
8+
* then return its index. Otherwise, return -1.
9+
*
10+
* You must write an algorithm with O(log n) runtime complexity.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @param {number} target
16+
* @return {number}
17+
*/
18+
var search = function(nums, target) {
19+
let left = 0;
20+
let right = nums.length - 1;
21+
22+
while (left <= right) {
23+
const pivot = Math.floor((right + left) / 2);
24+
if (nums[pivot] === target) return pivot;
25+
if (target < nums[pivot]) right = pivot - 1;
26+
else left = pivot + 1;
27+
}
28+
29+
return -1;
30+
};

0 commit comments

Comments
 (0)