intmySqrt(int a){ if (a == 0) return0; int l = 1, r = a, mid, sqrt; while (l <= r) { mid = l + (r - 1) / 2; sqrt = a / mid; if (sqrt == mid) { return mid; } elseif (mid > sqrt) { r = mid - 1; } else { l = mid + 1; } } return r; }
java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//注意int强转long的用法 classSolution{ publicintmySqrt(int x){ int l = 0; int r = x; int ans = -1; while (l <= r) { int mid = (l + r) / 2; if ((long)mid * mid <= x) { l = mid + 1; ans = mid; } else { r = mid - 1; } } return ans; } }
查找区间
Find First and Last Position of Element in Sorted Array (Medium)
//拆解为两个二分查找,注意收敛边界 classSolution{ publicint[] searchRange(int[] nums, int target) { int left = binarySearch(nums, target, true); int right = binarySearch(nums, target, false); returnnewint[]{left, right}; }
publicintbinarySearch(int[] nums, int target, Boolean leftFlag){ int result = -1; if (nums.length <= 0) { return result; } int left = 0; int right = nums.length - 1; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] == target && leftFlag && (0 == mid || nums[mid - 1] < nums[mid])) { return mid; } elseif (nums[mid] == target && !leftFlag && (mid == nums.length - 1 || nums[mid + 1] > nums[mid])) { return mid; } elseif ((leftFlag && nums[mid] >= target) || (!leftFlag && nums[mid] > target)) { right = mid - 1; } else { left = mid + 1; } } return result; } }