Skip to content

Commit 9a1a02a

Browse files
committed
Add solution #278
1 parent 55ede8b commit 9a1a02a

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@
9696
264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium|
9797
268|[Missing Number](./0268-missing-number.js)|Easy|
9898
273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard|
99+
278|[First Bad Version](./0278-first-bad-version.js)|Medium|
99100
283|[Move Zeroes](./0283-move-zeroes.js)|Easy|
100101
326|[Power of Three](./0326-power-of-three.js)|Easy|
101102
342|[Power of Four](./0342-power-of-four.js)|Easy|

Diff for: solutions/0278-first-bad-version.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 278. First Bad Version
3+
* https://leetcode.com/problems/first-bad-version/
4+
* Difficulty: Medium
5+
*
6+
* You are a product manager and currently leading a team to develop a new product.
7+
* Unfortunately, the latest version of your product fails the quality check. Since
8+
* each version is developed based on the previous version, all the versions after
9+
* a bad version are also bad.
10+
*
11+
* Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad
12+
* one, which causes all the following ones to be bad.
13+
*
14+
* You are given an API bool isBadVersion(version) which returns whether version is
15+
* bad. Implement a function to find the first bad version. You should minimize the
16+
* number of calls to the API.
17+
*/
18+
19+
/**
20+
* @param {function} isBadVersion()
21+
* @return {function}
22+
*/
23+
var solution = function(isBadVersion) {
24+
/**
25+
* @param {integer} n Total versions
26+
* @return {integer} The first bad version
27+
*/
28+
return n => {
29+
let left = 1;
30+
let right = n;
31+
32+
while (left <= right) {
33+
const pivot = Math.floor((right + left) / 2);
34+
if (isBadVersion(pivot)) {
35+
right = pivot - 1;
36+
} else {
37+
left = pivot + 1;
38+
}
39+
}
40+
41+
return left;
42+
};
43+
};

0 commit comments

Comments
 (0)