咸鱼算法日记——二分查找
二分查找只能用于有序表
有序想到二分查找
(一)二分查找的模板一
int binarySearch(int[] nums, int target){ if(nums == null || nums.length == 0) return -1; int left = 0, right = nums.length - 1; while(left <= right){ // Prevent (left + right) overflow int mid = left + (right - left) / 2; if(nums[mid] == target){ return mid; } else if(nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } // End Condition: left > right return -1; }
来自力扣专题。注意 中位数 的写法,为了防止整形溢出,left + (right - left)/2
在java的算法内,二分查找的中位数是这样的:(left+right)>>>1