[JS] First Bad Version
2022. 7. 29. 15:15
🔒 문제 (LeetCode 278)
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
Constraints:
- 1 <= bad <= n <= 2^31 - 1
🌊 입출력
Example 1:
Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
Example 2:
Input: n = 1, bad = 1
Output: 1
🔑 해결
🌌 알고리즘 - 이분탐색
/**
* Definition for isBadVersion()
*
* @param {integer} version number
* @return {boolean} whether the version is bad
* isBadVersion = function(version) {
* ...
* };
*/
/**
* @param {function} isBadVersion()
* @return {function}
*/
var solution = function(isBadVersion) {
/**
* @param {integer} n Total versions
* @return {integer} The first bad version
*/
return function(n) {
let left = 1;
let right = n;
while(left < right) {
let mid = left + right >>> 1;
if(isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return right;
};
};
'코딩테스트 (JS) > 이분탐색' 카테고리의 다른 글
[JS] Find First and Last Position of Element in Sorted Array (0) | 2022.08.04 |
---|---|
[JS] Search Insert Position (0) | 2022.07.29 |
[JS] 선입 선출 스케줄링 (0) | 2022.07.13 |
[JS] 금과 은 운반하기 (0) | 2022.07.06 |
[JS] 지형 편집 (0) | 2022.07.03 |