File tree Expand file tree Collapse file tree 2 files changed +31
-0
lines changed
Expand file tree Collapse file tree 2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change 125125686|[ Repeated String Match] ( ./0686-repeated-string-match.js ) |Easy|
126126700|[ Search in a Binary Search Tree] ( ./0700-search-in-a-binary-search-tree.js ) |Easy|
127127701|[ Insert into a Binary Search Tree] ( ./0701-insert-into-a-binary-search-tree.js ) |Medium|
128+ 704|[ Binary Search] ( ./0704-binary-search.js ) |Easy|
128129713|[ Subarray Product Less Than K] ( ./0713-subarray-product-less-than-k.js ) |Medium|
129130722|[ Remove Comments] ( ./0722-remove-comments.js ) |Medium|
130131739|[ Daily Temperatures] ( ./0739-daily-temperatures.js ) |Medium|
Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments