[LeetCode][278. First Bad Version] Java Binary Search Solution

By Long Luo

This article is the solution Java Binary Search Solution of Problem 278. First Bad Version.

Intuition

We can use Binary Search method to exclusive a half to reduce the scale Each Round.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int firstBadVersion(int n) {
int left = 1;
int right = n;

while (left < right) {
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
}

return left;
}

Analysis

  • Time Complexity: \(O(logn)\).
  • Space Complexity: \(O(1)\).

All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗