



1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public int binarySearch(int[] array, int des) { int low = 0, high = array.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (des == array[mid]) { return mid; } else if (des < array[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class Solution {
public int mySqrt(int x) { if (x == 0) { return 0; } long left = 1; long right = x / 2; while (left < right) { long mid = (left + right + 1) >>> 1; long square = mid * mid; if (square > x) { right = mid - 1; } else { left = mid; } } return (int) left; }
}
|
二分查找
Binary Search Solution in Leetcode
二分查找细节详解_labuladong