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

给定一个整型升序数组,找到一个给定值在数组中的位置区间。 你的算法复杂度必须低于O(logn)。 如果目标在数组中不会被发现,返回[-1, -1]。 例如,给定[5, 7, 7, 8, 8, 10],目标值为8,返回[3, 4]。

 1     public int[] searchRange(int[] nums, int target) {
 2         int[] result = {-1,-1};
 3         if (nums.length == 0) return result;
 4         int low = 0, high = nums.length - 1;
 5         while (low < high) {
 6             int mid = (low + high) / 2;
 7             if (nums[mid] < target) low = mid + 1;
 8             else  high = mid;
 9         }
10         if (nums[low]!=target) return result;
11         else result[0]=low;
12 
13         high = nums.length-1;  // We don't have to set i to 0 the second time.
14         while (low < high)
15         {
16             int mid = (low + high) /2 + 1;    // Make mid biased to the right
17             if (nums[mid] > target) high = mid - 1;
18             else low = mid;                // So that this won't make the search range stuck.
19         }
20         result[1] = high;
21         return result;       
22     }

 

posted @ 2017-10-16 08:24  daniel456  阅读(134)  评论(0编辑  收藏  举报