34. Search for a Range java solutions

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].

 

Subscribe to see which companies asked this questio

因为原数组是有序的,二分查找后,前后遍历即可。

 1 public class Solution {
 2     public int[] searchRange(int[] nums, int target) {
 3         int index = Arrays.binarySearch(nums,target);
 4         if(index < 0) return new int[]{-1,-1};
 5         int s = index - 1,e = index + 1;
 6         while(s >= 0 && nums[s] == nums[index]) s--;
 7         while(e < nums.length && nums[e] == nums[index]) e++;
 8         return new int[]{++s,--e};
 9     }
10 }

 

posted @ 2016-07-06 14:35  Miller1991  阅读(127)  评论(0编辑  收藏  举报