34. Search for a Range

Given an array of integers sorted in ascending order, 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].

本题开始确实能够想到二分查找,但是,却并不知道如何取得最左面和最右面值==target的索引,本题的二分查找是查找两次,一次是找最左面的值==target的索引,一次是找最右面的值==target的索引,拿最左面举例,以上题为例,在7,8之间进行划分,也就是说mid>=和mid<分成两种情况,接下来就是二分查找了,代码如下:

 1 public class Solution {
 2     public int[] searchRange(int[] nums, int target) {
 3         if(nums==null||nums.length==0) return new int[]{-1,-1};
 4         int left = 0;
 5         int right = nums.length-1;
 6         while(left<right){
 7             int mid = left +(right-left)/2;
 8             if(nums[mid]>=target){
 9                 right = mid;
10             }else{
11                 left = mid+1;
12             }
13         }
14         if(nums[left]!=target) return new int[]{-1,-1};
15         int left_index = left;
16         right = nums.length-1;
17         while(left<right){
18             int mid = left+(right-left)/2+1;
19             if(nums[mid]<=target) left  =mid;
20             else{
21                 right = mid-1;
22             }
23         }
24         int right_index = left;
25         return new int[]{left_index,right_index};
26     }
27 }
28 //the time complexity of this one could be O(logn), the space complexity could be O(1);
原文地址:https://www.cnblogs.com/codeskiller/p/6477930.html