Skip to content

Commit 1f21ca1

Browse files
committed
Add solution #374
1 parent 202aaeb commit 1f21ca1

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@
105105
347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium|
106106
349|[Intersection of Two Arrays](./0349-intersection-of-two-arrays.js)|Easy|
107107
350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy|
108+
374|[Guess Number Higher or Lower](./0374-guess-number-higher-or-lower.js)|Medium|
108109
383|[Ransom Note](./0383-ransom-note.js)|Easy|
109110
387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy|
110111
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 374. Guess Number Higher or Lower
3+
* https://leetcode.com/problems/guess-number-higher-or-lower/
4+
* Difficulty: Medium
5+
*
6+
* We are playing the Guess Game. The game is as follows:
7+
*
8+
* I pick a number from 1 to n. You have to guess which number I picked.
9+
*
10+
* Every time you guess wrong, I will tell you whether the number I picked is higher
11+
* or lower than your guess.
12+
*
13+
* You call a pre-defined API int guess(int num), which returns 3 possible results:
14+
* - -1: The number I picked is lower than your guess (i.e. pick < num).
15+
* - 1: The number I picked is higher than your guess (i.e. pick > num).
16+
* - 0: The number I picked is equal to your guess (i.e. pick == num).
17+
*
18+
* Return the number that I picked.
19+
*/
20+
21+
/**
22+
* Forward declaration of guess API.
23+
* @param {number} num your guess
24+
* @return -1 if num is lower than the guess number
25+
* 1 if num is higher than the guess number
26+
* otherwise return 0
27+
* var guess = function(num) {}
28+
*/
29+
30+
/**
31+
* @param {number} n
32+
* @return {number}
33+
*/
34+
var guessNumber = function(n) {
35+
let left = 1;
36+
let right = n;
37+
38+
while (left <= right) {
39+
const pivot = Math.floor((right + left) / 2);
40+
switch (guess(pivot)) {
41+
case -1: right = pivot - 1; break;
42+
case 1: left = pivot + 1; break;
43+
case 0: return pivot;
44+
}
45+
}
46+
};

0 commit comments

Comments
 (0)