[Leetcode] Search for a Range 寻找区间
Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example, Given
[5, 7, 7, 8, 8, 10]
and target value 8, return[3, 4]
.
二分搜索
复杂度
时间 O(logN) 空间 O(1)
思路
其实就是执行两次二分搜索,一次专门找左边边界,一次找右边边界。特别的,如果找左边边界时,要看mid左边一位的的数是否和当前mid相同,如果相同要继续在左半边二分搜索。如果找右边边界,则要判断右边一位的数是否相同。
代码
public class Solution { public int[] searchRange(int[] nums, int target) { // 找到左边界 int front = search(nums, target, "front"); // 找到右边界 int rear = search(nums, target, "rear"); int[] res = {front, rear}; return res; } public int search(int[] nums, int target, String type){ int min = 0, max = nums.length - 1; while(min <= max){int mid = min + (max - min) / 2;if(nums[mid] > target){ max = mid - 1;} else if(nums[mid] < target){ min = mid + 1;} else { // 对于找左边的情况,要判断左边的数是否重复 if(type == "front"){ if(mid == 0) return 0; if(nums[mid] != nums[mid - 1]) return mid; max = mid - 1; } else { // 对于找右边的情况,要判断右边的数是否重复 if(mid == nums.length - 1) return nums.length - 1; if(nums[mid] != nums[mid + 1]) return mid; min = mid + 1; }} } //没找到该数返回-1 return -1; }}