https://github.com/emahtab/first-bad-version
https://github.com/emahtab/first-bad-version
binary-search leetcode
Last synced: 4 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/emahtab/first-bad-version
- Owner: eMahtab
- Created: 2022-01-09T13:11:36.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-01-09T14:00:00.000Z (over 3 years ago)
- Last Synced: 2025-02-02T03:25:41.057Z (5 months ago)
- Topics: binary-search, leetcode
- Homepage:
- Size: 1.95 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# First bad version
## https://leetcode.com/problems/first-bad-version# Implementation 1 : Naive(Brute Force) Time Limit Exceeded O(n)
```java
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */public class Solution extends VersionControl {
public int firstBadVersion(int n) {
for(int i = 1; i <= n; i++) {
if(isBadVersion(i))
return i;
}
return -1;
}
}
```# Implementation 2 : Binary Search O(logn)
```java
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int left = 1;
int right = n;
while(left < right) {
int mid = left + (right-left)/2;
if(!isBadVersion(mid)) {
left = mid+1;
} else {
right = mid;
}
}
return left;
}
}
```# References :
https://leetcode.com/problems/first-bad-version/solution