https://leetcode-/problems/find-first-and-last-position-of-element-in-sorted-array/
解决方案
class Solution {public int[] searchRange(int[] nums, int target) {int leftIdx = binarySearch(nums, target, 0, true);return new int[]{leftIdx, binarySearch(nums, target, leftIdx, false)};}public int binarySearch(int[] nums, int target, int left, boolean lower) {if (left == -1) {return -1;}int ans = -1;int right = nums.length - 1;while (left <= right) {int mid = (left + right) / 2;if (nums[mid] == target) {if (lower) {right = mid - 1;} else {left = mid + 1;}ans = mid;} else if (nums[mid] > target) {right = mid - 1;} else {left = mid + 1;}}return ans;}}
如果觉得《LeetCode 34 在排序数组中查找元素的第一个和最后一个位置》对你有帮助,请点赞、收藏,并留下你的观点哦!