二分查找算法思路如下:确定要查找的数组nums的左下标left,右下标right。根据left,right计算出中间下标mid。比较nums[mid]和target值,再根据比较的情况,重新确定要查找的数组的边界。即重复上述步骤。直到找到想要找的数,或者没找到(循环退出)。JAVA代码如下:
public int search(int[] nums, int target) { int left = 0; int right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { left = mid + 1; } else if (nums[mid] > target) { right = mid - 1; } } return -1; }
代码的关键在于三个细节