提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣34. 在排序数组中查找元素的第一个和最后一个位置
前言
一文搞懂二分查找,左闭右闭,或者左闭右开,以及寻找左右边界
一、力扣34. 在排序数组中查找元素的第一个和最后一个位置
class Solution {public int[] searchRange(int[] nums, int target) {int[] res = new int[]{-1,-1};int left = 0, right = nums.length-1;while(left <= right){int mid = left + (right-left)/2;if(nums[mid] == target){right = mid-1;}else if(nums[mid] > target){right = mid -1;}else{left = mid+1;}}if(left >= 0 && left <= nums.length-1){res[0] = nums[left] == target ? left : -1;}left = 0; right = nums.length-1;while(left <= right){int mid = left + (right-left)/2;if(nums[mid] == target){left = mid+1;}else if(nums[mid] > target){right = mid -1;}else{left = mid + 1;}}if(right >= 0 && right <= nums.length-1){res[1] = nums[right] == target ? right : -1;}return res;}
}