public int binarySearch(int[] nums, int target) { int left = 0, 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 { right = mid - 1; // 目标值在左半部分 } } return -1; // 未找到目标值 }
2.寻找左边界的二分查找模板
1 2 3 4 5 6 7 8 9 10 11 12
public int leftBound(int[] nums, int target) { int left = 0, right = nums.length; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] < target) { left = mid + 1; // 目标值在右半部分 } else { right = mid; // 目标值在左半部分 } } return left; // 返回左边界索引 }
3. 寻找右边界的二分查找模板
1 2 3 4 5 6 7 8 9 10 11 12
public int rightBound(int[] nums, int target) { int left = 0, right = nums.length; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] <= target) { left = mid + 1; // 目标值在右半部分 } else { right = mid; // 目标值在左半部分 } } return left - 1; // 返回右边界索引 }
4. 二分查找变体模板1(寻找第一个满足条件的值):
1 2 3 4 5 6 7 8 9 10 11 12
public int firstPosition(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] < target) { left = mid + 1; // 目标值在右半部分 } else { right = mid; // 目标值在左半部分 } } return nums[left] == target ? left : -1; // 返回第一个满足条件的值的索引 }
5. 二分查找变体模板2(寻找最后一个满足条件的值):
1 2 3 4 5 6 7 8 9 10 11 12
public int lastPosition(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left < right) { int mid = left + (right - left + 1) / 2; if (nums[mid] > target) { right = mid - 1; // 目标值在左半部分 } else { left = mid; // 目标值在右半部分 } } return nums[left] == target ? left : -1; // 返回最后一个满足条件的值的索引 }
//简代码 int L = 0; int R = nums.length; while(L+1 < R) { int M = (L+R)/2//如果数字大时可以使用 M = L +(R-L)/2; if (isblue(m)) { L = M; } else { R = M ; } } return L/R //根据实际情况情况选择
class Solution { public int searchRangeLeft(int[] nums, int target) { int left = -1; int right =nums.length; while (left+1 != right) { int mid = (left + right) / 2; if(nums[mid] <= target) { left = mid; }else { right = mid; } } return left; } public int searchRangeRight(int[] nums, int target) { int left = -1; int right =nums.length; while (left+1 != right) { int mid = (left + right) / 2; if(nums[mid] < target) { left = mid; }else { right = mid; } } return right; } public int[] searchRange(int[] nums, int target) { int leftIndex = searchRangeLeft(nums,target); int rightIndex = searchRangeRight(nums,target); if(leftIndex >= rightIndex && leftIndex < nums.length && nums[leftIndex] == target && nums[rightIndex] == target) { return new int[] {rightIndex,leftIndex}; } return new int[] {-1,-1}; } }