Back to course home
0% completed
Vote For New Content
Potential Slightly Easier To Understand
Oct 14, 2023
I just wanted to suggest a more subtle way of explaining it that may be a bit better. So, binary search is applied here because we are searching for a value in a specific range of values, which is a range of sorted numbers. That value we are looking for is the largest value n such that n * n <= x. So, we can use a variable to store the result, and if we ever find a value whose square is <= x, update the result to that. However, since our goal is to find the largest, toss that pivot out and set left = mid + 1. If the square is too large, then we want to lower our right bound and set right = mid - 1.
class Solution { public int mySqrt(int x) { int left = 0; int right = x; int res = 0; while(left <= right){ int mid = left + (right - left) / 2; if((long) mid * mid <= x){ res = mid; left = mid + 1; } else{ right = mid - 1; } } return res; } }
9
0
Comments
Comments
L
lejafilip a year ago
Much better, because original solution is unintuitive
On this page