题目:给定一个排序数组,找出给定的target值出现的范围;算法复杂度要求在O(logn);如果没有找到,则返回[-1, -1];
举例:
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
解题思路:
一看到题目要求的时间复杂度O(logn),就自然想要要用到二分的方法,这道题目,我们自然也是用二分的方法;
mid = (start + end) / 2;则target和nums[mid]的关系有三种:
1) target <nums[mid],则后半部分就被舍弃掉了, end = mid - 1;
2) target > nums[mid], 则前半部分就被舍弃掉了, start = mid + 1;
3) target = nums[mid],这种情况不能单纯的舍弃掉哪一半,而是要从中间向两端遍历,直到找到边界为止;
代码如下:
1 public class Solution { 2 public int[] searchRange(int[] nums, int target) { 3 if(nums == null || nums.length < 1) 4 return new int[]{-1, -1}; 5 int[] res = new int[2]; 6 res[0] = -1; 7 res[1] = -1; 8 int start = 0; 9 int end = nums.length - 1; 10 int mid = 0; 11 while(start <= end) 12 { 13 mid = (start + end) / 2; 14 if(nums[mid] < target) 15 start = mid + 1; 16 else if(nums[mid] > target) 17 end = mid - 1; 18 else 19 { 20 start = mid; 21 end = mid; 22 while(start >= 0 && nums[start] == target) 23 start--; 24 while(end < nums.length && nums[end] == target) 25 end++; 26 return new int[]{start + 1, end - 1}; 27 } 28 } 29 return res; 30 } 31 }
时间: 2024-10-01 04:05:55