34.在排序数组中查找元素的第一个和最后一个位置
二分查找中,寻找 leftIdx 即为在数组中寻找第一个大于等于 target 的下标,寻找 rightIdx 即为在数组中寻找第一个大于 target 的下标,然后将下标减一。进行两次查找
class Solution {public int[] searchRange(int[] nums, int target) {//寻找左边界int leftIndex = search(nums,target);if(leftIndex >= nums.length || nums[leftIndex] != target){return new int[]{-1,-1};}//寻找右边界int rightIndex = search(nums,target + 1);return new int[]{leftIndex, rightIndex - 1};}private int search(int[] nums, int target) {int left = 0;int right = nums.length - 1;while (left <= right){int mid = (right + left) / 2 ;if (nums[mid] >= target){right = mid - 1;} else {left = mid + 1;}}return left;}}